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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.112! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.111 2019/08/19 17:35:34 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.1172.2.112! raeburn   900:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  901: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  902: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  903: 	}
                    904: 	closedir(LONIDS);
                    905:     }
                    906:     my $userloadpercent=0;
                    907:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    908:     if ($maxuserload) {
1.371     albertel  909: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  910:     }
1.372     albertel  911:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  912:     return $userloadpercent;
1.283     www       913: }
                    914: 
1.1       albertel  915: # ------------------------------ Find server with least workload from spare.tab
1.11      www       916: 
1.1       albertel  917: sub spareserver {
1.1083    raeburn   918:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  919:     my $spare_server;
1.370     albertel  920:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  921:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    922:                                                      :  $userloadpercent;
1.1083    raeburn   923:     my ($uint_dom,$remotesessions);
                    924:     if (($udom ne '') && (&domain($udom) ne '')) {
                    925:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    926:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    927:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    928:         $remotesessions = $udomdefaults{'remotesessions'};
                    929:     }
1.1123    raeburn   930:     my $spareshash = &this_host_spares($udom);
                    931:     if (ref($spareshash) eq 'HASH') {
                    932:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    933:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   934:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    935:                                              $try_server));
1.1123    raeburn   936: 	        ($spare_server, $lowest_load) =
                    937: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    938:             }
1.1083    raeburn   939:         }
1.784     albertel  940: 
1.1123    raeburn   941:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    942: 
                    943:         if (!$found_server) {
                    944:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    945: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   946:                     next unless (&spare_can_host($udom,$uint_dom,
                    947:                                                  $remotesessions,$try_server));
1.1123    raeburn   948: 	            ($spare_server, $lowest_load) =
                    949: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    950:                 }
                    951: 	    }
                    952:         }
1.784     albertel  953:     }
                    954: 
                    955:     if (!$want_server_name) {
1.968     raeburn   956:         my $protocol = 'http';
                    957:         if ($protocol{$spare_server} eq 'https') {
                    958:             $protocol = $protocol{$spare_server};
                    959:         }
1.1001    raeburn   960:         if (defined($spare_server)) {
                    961:             my $hostname = &hostname($spare_server);
1.1083    raeburn   962:             if (defined($hostname)) {
1.1001    raeburn   963: 	        $spare_server = $protocol.'://'.$hostname;
                    964:             }
                    965:         }
1.784     albertel  966:     }
                    967:     return $spare_server;
                    968: }
                    969: 
                    970: sub compare_server_load {
1.1172.2.41  raeburn   971:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    972: 
                    973:     if ($required) {
                    974:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    975:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    976:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    977:         if (($major eq '' && $minor eq '') ||
                    978:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    979:             return ($spare_server,$lowest_load);
                    980:         }
                    981:     }
1.784     albertel  982: 
                    983:     my $loadans     = &reply('load',    $try_server);
                    984:     my $userloadans = &reply('userload',$try_server);
                    985: 
                    986:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   987: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  988:     }
                    989: 
                    990:     my $load;
                    991:     if ($loadans =~ /\d/) {
                    992: 	if ($userloadans =~ /\d/) {
                    993: 	    #both are numbers, pick the bigger one
                    994: 	    $load = ($loadans > $userloadans) ? $loadans 
                    995: 		                              : $userloadans;
1.411     albertel  996: 	} else {
1.784     albertel  997: 	    $load = $loadans;
1.411     albertel  998: 	}
1.784     albertel  999:     } else {
                   1000: 	$load = $userloadans;
                   1001:     }
                   1002: 
                   1003:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1004: 	$spare_server = $try_server;
                   1005: 	$lowest_load  = $load;
1.370     albertel 1006:     }
1.784     albertel 1007:     return ($spare_server,$lowest_load);
1.202     matthew  1008: }
1.914     albertel 1009: 
                   1010: # --------------------------- ask offload servers if user already has a session
                   1011: sub find_existing_session {
                   1012:     my ($udom,$uname) = @_;
1.1123    raeburn  1013:     my $spareshash = &this_host_spares($udom);
                   1014:     if (ref($spareshash) eq 'HASH') {
                   1015:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1016:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1017:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1018:             }
                   1019:         }
                   1020:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1021:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1022:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1023:             }
                   1024:         }
1.914     albertel 1025:     }
                   1026:     return;
                   1027: }
                   1028: 
1.1172.2.107  raeburn  1029: # check if user's browser sent load balancer cookie and server still has session
                   1030: # and is not overloaded.
                   1031: sub check_for_balancer_cookie {
                   1032:     my ($r,$update_mtime) = @_;
                   1033:     my ($otherserver,$cookie);
                   1034:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1035:     if (exists($cookies{'balanceID'})) {
                   1036:         my $balid = $cookies{'balanceID'};
                   1037:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1038:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1039:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1040:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1041:                 my ($possudom,$possuname) = ($1,$2);
                   1042:                 my $has_session = 0;
                   1043:                 if ((&domain($possudom) ne '') &&
                   1044:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1045:                     my $try_server;
                   1046:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1047:                     if ($opened) {
                   1048:                         flock($idf,LOCK_SH);
                   1049:                         while (my $line = <$idf>) {
                   1050:                             chomp($line);
                   1051:                             if (&hostname($line) ne '') {
                   1052:                                 $try_server = $line;
                   1053:                                 last;
                   1054:                             }
                   1055:                         }
                   1056:                         close($idf);
                   1057:                         if (($try_server) &&
                   1058:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1059:                             my $lowest_load = 30000;
                   1060:                             ($otherserver,$lowest_load) =
                   1061:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1062:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1063:                                 $has_session = 1;
                   1064:                             } else {
                   1065:                                 undef($otherserver);
                   1066:                             }
                   1067:                         }
                   1068:                     }
                   1069:                 }
                   1070:                 if ($has_session) {
                   1071:                     if ($update_mtime) {
                   1072:                         my $atime = my $mtime = time;
                   1073:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1074:                     }
                   1075:                 } else {
                   1076:                     unlink("$balancedir/$cookie.id");
                   1077:                 }
                   1078:             }
                   1079:         }
                   1080:     }
                   1081:     return ($otherserver,$cookie);
                   1082: }
                   1083: 
                   1084: sub delbalcookie {
                   1085:     my ($cookie,$balancer) =@_;
                   1086:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1087:         my ($udom,$uname) = ($1,$2);
                   1088:         my $uprimary_id = &domain($udom,'primary');
                   1089:         my $uintdom = &internet_dom($uprimary_id);
                   1090:         my $intdom = &internet_dom($balancer);
                   1091:         my $serverhomedom = &host_domain($balancer);
                   1092:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1093:             return &reply("delbalcookie:$cookie",$balancer);
                   1094:         }
                   1095:     }
                   1096: }
                   1097: 
1.914     albertel 1098: # -------------------------------- ask if server already has a session for user
                   1099: sub has_user_session {
                   1100:     my ($lonid,$udom,$uname) = @_;
                   1101:     my $result = &reply(join(':','userhassession',
                   1102: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1103:     return 1 if ($result eq 'ok');
                   1104: 
                   1105:     return 0;
                   1106: }
                   1107: 
1.1076    raeburn  1108: # --------- determine least loaded server in a user's domain which allows login
                   1109: 
                   1110: sub choose_server {
1.1172.2.47  raeburn  1111:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1112:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1113:     my %servers = &get_servers($udom);
1.1076    raeburn  1114:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1115:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1116:     if ($skiploadbal) {
                   1117:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1118:         unless (defined($cached)) {
                   1119:             my $cachetime = 60*60*24;
                   1120:             my %domconfig =
                   1121:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1122:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1123:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1124:                                            $cachetime);
                   1125:             }
                   1126:         }
                   1127:     }
1.1076    raeburn  1128:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1129:         my $loginvia;
1.1172.2.47  raeburn  1130:         if ($skiploadbal) {
                   1131:             if (ref($balancers) eq 'HASH') {
                   1132:                 next if (exists($balancers->{$lonhost}));
                   1133:             }
                   1134:         }
1.1115    raeburn  1135:         if ($checkloginvia) {
                   1136:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1137:             if ($loginvia) {
                   1138:                 my ($server,$path) = split(/:/,$loginvia);
                   1139:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1140:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1141:                 if ($login_host eq $server) {
                   1142:                     $portal_path = $path;
1.1151    raeburn  1143:                     $isredirect = 1;
1.1116    raeburn  1144:                 }
                   1145:             } else {
                   1146:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1147:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1148:                 if ($login_host eq $lonhost) {
                   1149:                     $portal_path = '';
1.1151    raeburn  1150:                     $isredirect = ''; 
1.1116    raeburn  1151:                 }
                   1152:             }
                   1153:         } else {
1.1076    raeburn  1154:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1155:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1156:         }
                   1157:     }
                   1158:     if ($login_host ne '') {
1.1116    raeburn  1159:         $hostname = &hostname($login_host);
1.1076    raeburn  1160:     }
1.1172.2.88  raeburn  1161:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1162: }
                   1163: 
1.202     matthew  1164: # --------------------------------------------- Try to change a user's password
                   1165: 
                   1166: sub changepass {
1.799     raeburn  1167:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1168:     $currentpass = &escape($currentpass);
                   1169:     $newpass     = &escape($newpass);
1.1030    raeburn  1170:     my $lonhost = $perlvar{'lonHostID'};
                   1171:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1172: 		       $server);
                   1173:     if (! $answer) {
                   1174: 	&logthis("No reply on password change request to $server ".
                   1175: 		 "by $uname in domain $udom.");
                   1176:     } elsif ($answer =~ "^ok") {
                   1177:         &logthis("$uname in $udom successfully changed their password ".
                   1178: 		 "on $server.");
                   1179:     } elsif ($answer =~ "^pwchange_failure") {
                   1180: 	&logthis("$uname in $udom was unable to change their password ".
                   1181: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1182: 		 "or pwchange");
                   1183:     } elsif ($answer =~ "^non_authorized") {
                   1184:         &logthis("$uname in $udom did not get their password correct when ".
                   1185: 		 "attempting to change it on $server.");
                   1186:     } elsif ($answer =~ "^auth_mode_error") {
                   1187:         &logthis("$uname in $udom attempted to change their password despite ".
                   1188: 		 "not being locally or internally authenticated on $server.");
                   1189:     } elsif ($answer =~ "^unknown_user") {
                   1190:         &logthis("$uname in $udom attempted to change their password ".
                   1191: 		 "on $server but were unable to because $server is not ".
                   1192: 		 "their home server.");
                   1193:     } elsif ($answer =~ "^refused") {
                   1194: 	&logthis("$server refused to change $uname in $udom password because ".
                   1195: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1196:     } elsif ($answer =~ "invalid_client") {
                   1197:         &logthis("$server refused to change $uname in $udom password because ".
                   1198:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1199:     }
                   1200:     return $answer;
1.1       albertel 1201: }
                   1202: 
1.169     harris41 1203: # ----------------------- Try to determine user's current authentication scheme
                   1204: 
                   1205: sub queryauthenticate {
                   1206:     my ($uname,$udom)=@_;
1.456     albertel 1207:     my $uhome=&homeserver($uname,$udom);
                   1208:     if (!$uhome) {
                   1209: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1210: 	return 'no_host';
                   1211:     }
                   1212:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1213:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1214: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1215:     }
1.456     albertel 1216:     return $answer;
1.169     harris41 1217: }
                   1218: 
1.1       albertel 1219: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1220: 
1.1       albertel 1221: sub authenticate {
1.1073    raeburn  1222:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1223:     $upass=&escape($upass);
                   1224:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1225:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1226:     my $newhome;
1.836     www      1227:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1228: # Maybe the machine was offline and only re-appeared again recently?
                   1229:         &reconlonc();
                   1230: # One more
1.952     raeburn  1231: 	$uhome=&homeserver($uname,$udom,1);
                   1232:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1233:             if (defined(&domain($udom,'primary'))) {
                   1234:                 $newhome=&domain($udom,'primary');
                   1235:             }
                   1236:             if ($newhome ne '') {
                   1237:                 $uhome = $newhome;
                   1238:             }
                   1239:         }
1.836     www      1240: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1241: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1242: 	    return 'no_host';
                   1243:         }
1.1       albertel 1244:     }
1.1073    raeburn  1245:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1246:     if ($answer eq 'authorized') {
1.952     raeburn  1247:         if ($newhome) {
                   1248:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1249:             return 'no_account_on_host'; 
                   1250:         } else {
                   1251:             &logthis("User $uname at $udom authorized by $uhome");
                   1252:             return $uhome;
                   1253:         }
1.471     albertel 1254:     }
                   1255:     if ($answer eq 'non_authorized') {
                   1256: 	&logthis("User $uname at $udom rejected by $uhome");
                   1257: 	return 'no_host'; 
1.9       www      1258:     }
1.471     albertel 1259:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1260:     return 'no_host';
                   1261: }
                   1262: 
1.1073    raeburn  1263: sub can_host_session {
1.1074    raeburn  1264:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1265:     my $canhost = 1;
1.1074    raeburn  1266:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1267:     if (ref($remotesessions) eq 'HASH') {
                   1268:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1269:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1270:                 $canhost = 0;
                   1271:             } else {
                   1272:                 $canhost = 1;
                   1273:             }
                   1274:         }
                   1275:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1276:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1277:                 $canhost = 1;
                   1278:             } else {
                   1279:                 $canhost = 0;
                   1280:             }
                   1281:         }
                   1282:         if ($canhost) {
                   1283:             if ($remotesessions->{'version'} ne '') {
                   1284:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1285:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1286:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1287:                         my $major = $1;
                   1288:                         my $minor = $2;
                   1289:                         if (($major < $reqmajor ) ||
                   1290:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1291:                             $canhost = 0;
                   1292:                         }
                   1293:                     } else {
                   1294:                         $canhost = 0;
                   1295:                     }
                   1296:                 }
                   1297:             }
                   1298:         }
                   1299:     }
                   1300:     if ($canhost) {
                   1301:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1302:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1303:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1304:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1305:                 if (($uint_dom ne '') && 
                   1306:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1307:                     $canhost = 0;
                   1308:                 } else {
                   1309:                     $canhost = 1;
                   1310:                 }
                   1311:             }
                   1312:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1313:                 if (($uint_dom ne '') && 
                   1314:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1315:                     $canhost = 1;
                   1316:                 } else {
                   1317:                     $canhost = 0;
                   1318:                 }
                   1319:             }
                   1320:         }
                   1321:     }
                   1322:     return $canhost;
                   1323: }
                   1324: 
1.1083    raeburn  1325: sub spare_can_host {
                   1326:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1327:     my $canhost=1;
1.1172.2.62  raeburn  1328:     my $try_server_hostname = &hostname($try_server);
                   1329:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1330:     my $serverhomedom = &host_domain($serverhomeID);
                   1331:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1332:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1333:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1334:             $canhost = 0;
                   1335:         }
                   1336:     }
                   1337:     if (($canhost) && ($uint_dom)) {
                   1338:         my @intdoms;
                   1339:         my $internet_names = &get_internet_names($try_server);
                   1340:         if (ref($internet_names) eq 'ARRAY') {
                   1341:             @intdoms = @{$internet_names};
                   1342:         }
                   1343:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1344:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1345:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1346:                                          $remotesessions,
                   1347:                                          $defdomdefaults{'hostedsessions'});
                   1348:         }
1.1083    raeburn  1349:     }
                   1350:     return $canhost;
                   1351: }
                   1352: 
1.1123    raeburn  1353: sub this_host_spares {
                   1354:     my ($dom) = @_;
1.1126    raeburn  1355:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1356:     my @hosts = &current_machine_ids();
                   1357:     foreach my $lonhost (@hosts) {
                   1358:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1359:             $dom_in_use = $dom;
                   1360:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1361:             last;
                   1362:         }
                   1363:     }
1.1126    raeburn  1364:     if ($dom_in_use ne '') {
                   1365:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1366:     }
                   1367:     if (ref($result) ne 'HASH') {
                   1368:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1369:         $dom_in_use = &host_domain($lonhost_in_use);
                   1370:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1371:         if (ref($result) ne 'HASH') {
                   1372:             $result = \%spareid;
                   1373:         }
                   1374:     }
                   1375:     return $result;
                   1376: }
                   1377: 
                   1378: sub spares_for_offload  {
                   1379:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1380:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1381:     if (defined($cached)) {
                   1382:         return $result;
                   1383:     } else {
1.1126    raeburn  1384:         my $cachetime = 60*60*24;
                   1385:         my %domconfig =
                   1386:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1387:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1388:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1389:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1390:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1391:                 }
                   1392:             }
                   1393:         }
                   1394:     }
1.1126    raeburn  1395:     return;
1.1123    raeburn  1396: }
                   1397: 
1.1129    raeburn  1398: sub get_lonbalancer_config {
                   1399:     my ($servers) = @_;
                   1400:     my ($currbalancer,$currtargets);
                   1401:     if (ref($servers) eq 'HASH') {
                   1402:         foreach my $server (keys(%{$servers})) {
                   1403:             my %what = (
                   1404:                          spareid => 1,
                   1405:                          perlvar => 1,
                   1406:                        );
                   1407:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1408:             if ($result eq 'ok') {
                   1409:                 if (ref($returnhash) eq 'HASH') {
                   1410:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1411:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1412:                             $currbalancer = $server;
                   1413:                             $currtargets = {};
                   1414:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1415:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1416:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1417:                                 }
                   1418:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1419:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1420:                                 }
                   1421:                             }
                   1422:                             last;
                   1423:                         }
                   1424:                     }
                   1425:                 }
                   1426:             }
                   1427:         }
                   1428:     }
                   1429:     return ($currbalancer,$currtargets);
                   1430: }
                   1431: 
                   1432: sub check_loadbalancing {
1.1172.2.88  raeburn  1433:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1434:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1435:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1436:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1437:     my @hosts = &current_machine_ids();
1.1129    raeburn  1438:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1439:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1440:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1441:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1442:     my $domneedscache; 
1.1129    raeburn  1443:     my $cachetime = 60*60*24;
                   1444: 
                   1445:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1446:         $dom_in_use = $udom;
                   1447:         $homeintdom = 1;
                   1448:     } else {
                   1449:         $dom_in_use = $serverhomedom;
                   1450:     }
                   1451:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1452:     unless (defined($cached)) {
                   1453:         my %domconfig =
                   1454:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1455:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1456:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1457:         } else {
                   1458:             $domneedscache = $dom_in_use;
1.1129    raeburn  1459:         }
                   1460:     }
                   1461:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1462:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1463:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1464:         if ($is_balancer) {
                   1465:             if (ref($currrules) eq 'HASH') {
                   1466:                 if ($homeintdom) {
                   1467:                     if ($uname ne '') {
                   1468:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1469:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1470:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1471:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1472:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1473:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1474:                             }
                   1475:                         }
                   1476:                         if ($rule_in_effect eq '') {
                   1477:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1478:                             if ($userenv{'inststatus'} ne '') {
                   1479:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1480:                                 my ($othertitle,$usertypes,$types) =
                   1481:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1482:                                 if (ref($types) eq 'ARRAY') {
                   1483:                                     foreach my $type (@{$types}) {
                   1484:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1485:                                             if (exists($currrules->{$type})) {
                   1486:                                                 $rule_in_effect = $currrules->{$type};
                   1487:                                             }
                   1488:                                         }
                   1489:                                     }
                   1490:                                 }
                   1491:                             } else {
                   1492:                                 if (exists($currrules->{'default'})) {
                   1493:                                     $rule_in_effect = $currrules->{'default'};
                   1494:                                 }
                   1495:                             }
                   1496:                         }
                   1497:                     } else {
                   1498:                         if (exists($currrules->{'default'})) {
                   1499:                             $rule_in_effect = $currrules->{'default'};
                   1500:                         }
                   1501:                     }
                   1502:                 } else {
                   1503:                     if ($currrules->{'_LC_external'} ne '') {
                   1504:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1505:                     }
                   1506:                 }
                   1507:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1508:                                                        $uname,$udom);
                   1509:             }
                   1510:         }
                   1511:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1512:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1513:         unless (defined($cached)) {
                   1514:             my %domconfig =
                   1515:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1516:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1517:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1518:             } else {
                   1519:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1520:             }
                   1521:         }
                   1522:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1523:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1524:                 &check_balancer_result($result,@hosts);
                   1525:             if ($is_balancer) {
1.1129    raeburn  1526:                 if (ref($currrules) eq 'HASH') {
                   1527:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1528:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1529:                     }
                   1530:                 }
                   1531:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1532:                                                        $uname,$udom);
                   1533:             }
                   1534:         } else {
                   1535:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1536:                 $is_balancer = 1;
                   1537:                 $offloadto = &this_host_spares($dom_in_use);
                   1538:             }
1.1172.2.75  raeburn  1539:             unless (defined($cached)) {
                   1540:                 $domneedscache = $serverhomedom;
                   1541:             }
1.1129    raeburn  1542:         }
                   1543:     } else {
                   1544:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1545:             $is_balancer = 1;
                   1546:             $offloadto = &this_host_spares($dom_in_use);
                   1547:         }
1.1172.2.75  raeburn  1548:         unless (defined($cached)) {
                   1549:             $domneedscache = $serverhomedom;
                   1550:         }
                   1551:     }
                   1552:     if ($domneedscache) {
                   1553:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1554:     }
1.1172.2.5  raeburn  1555:     if ($is_balancer) {
                   1556:         my $lowest_load = 30000;
                   1557:         if (ref($offloadto) eq 'HASH') {
                   1558:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1559:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1560:                     ($otherserver,$lowest_load) =
                   1561:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1562:                 }
1.1129    raeburn  1563:             }
1.1172.2.5  raeburn  1564:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1565: 
1.1172.2.5  raeburn  1566:             if (!$found_server) {
                   1567:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1568:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1569:                         ($otherserver,$lowest_load) =
                   1570:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1571:                     }
                   1572:                 }
                   1573:             }
                   1574:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1575:             if (@{$offloadto} == 1) {
                   1576:                 $otherserver = $offloadto->[0];
                   1577:             } elsif (@{$offloadto} > 1) {
                   1578:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1579:                     ($otherserver,$lowest_load) =
                   1580:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1581:                 }
                   1582:             }
                   1583:         }
1.1172.2.88  raeburn  1584:         unless ($caller eq 'login') {
                   1585:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1586:                 $is_balancer = 0;
                   1587:                 if ($uname ne '' && $udom ne '') {
                   1588:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1589:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1590:                                  'user.loadbalcheck.time' => time});
                   1591:                     }
1.1172.2.5  raeburn  1592:                 }
1.1129    raeburn  1593:             }
                   1594:         }
1.1172.2.107  raeburn  1595:         unless ($homeintdom) {
                   1596:             undef($setcookie);
                   1597:         }
1.1129    raeburn  1598:     }
1.1172.2.107  raeburn  1599:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1600: }
                   1601: 
1.1172.2.12  raeburn  1602: sub check_balancer_result {
                   1603:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1604:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1605:     if (ref($result) eq 'HASH') {
                   1606:         if ($result->{'lonhost'} ne '') {
                   1607:             my $currbalancer = $result->{'lonhost'};
                   1608:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1609:                 $is_balancer = 1;
                   1610:                 $currtargets = $result->{'targets'};
                   1611:                 $currrules = $result->{'rules'};
                   1612:             }
                   1613:         } else {
                   1614:             foreach my $key (keys(%{$result})) {
                   1615:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1616:                     (ref($result->{$key}) eq 'HASH')) {
                   1617:                     $is_balancer = 1;
                   1618:                     $currrules = $result->{$key}{'rules'};
                   1619:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1620:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1621:                     last;
                   1622:                 }
                   1623:             }
                   1624:         }
                   1625:     }
1.1172.2.107  raeburn  1626:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1627: }
                   1628: 
1.1129    raeburn  1629: sub get_loadbalancer_targets {
                   1630:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1631:     my $offloadto;
1.1172.2.4  raeburn  1632:     if ($rule_in_effect eq 'none') {
                   1633:         return [$perlvar{'lonHostID'}];
                   1634:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1635:         $offloadto = $currtargets;
                   1636:     } else {
                   1637:         if ($rule_in_effect eq 'homeserver') {
                   1638:             my $homeserver = &homeserver($uname,$udom);
                   1639:             if ($homeserver ne 'no_host') {
                   1640:                 $offloadto = [$homeserver];
                   1641:             }
                   1642:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1643:             my %domconfig =
                   1644:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1645:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1646:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1647:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1648:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1649:                     }
                   1650:                 }
                   1651:             } else {
1.1172.2.7  raeburn  1652:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1653:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1654:                 if (&hostname($remotebalancer) ne '') {
                   1655:                     $offloadto = [$remotebalancer];
                   1656:                 }
                   1657:             }
                   1658:         } elsif (&hostname($rule_in_effect) ne '') {
                   1659:             $offloadto = [$rule_in_effect];
                   1660:         }
                   1661:     }
                   1662:     return $offloadto;
                   1663: }
                   1664: 
1.1127    raeburn  1665: sub internet_dom_servers {
                   1666:     my ($dom) = @_;
                   1667:     my (%uniqservers,%servers);
                   1668:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1669:     my @machinedoms = &machine_domains($primaryserver);
                   1670:     foreach my $mdom (@machinedoms) {
                   1671:         my %currservers = %servers;
                   1672:         my %server = &get_servers($mdom);
                   1673:         %servers = (%currservers,%server);
                   1674:     }
                   1675:     my %by_hostname;
                   1676:     foreach my $id (keys(%servers)) {
                   1677:         push(@{$by_hostname{$servers{$id}}},$id);
                   1678:     }
                   1679:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1680:         if (@{$by_hostname{$hostname}} > 1) {
                   1681:             my $match = 0;
                   1682:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1683:                 if (&host_domain($id) eq $dom) {
                   1684:                     $uniqservers{$id} = $hostname;
                   1685:                     $match = 1;
                   1686:                 }
                   1687:             }
                   1688:             unless ($match) {
                   1689:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1690:             }
                   1691:         } else {
                   1692:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1693:         }
                   1694:     }
                   1695:     return %uniqservers;
                   1696: }
                   1697: 
1.1       albertel 1698: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1699: 
1.599     albertel 1700: my %homecache;
1.1       albertel 1701: sub homeserver {
1.230     stredwic 1702:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1703:     my $index="$uname:$udom";
1.426     albertel 1704: 
1.599     albertel 1705:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1706: 
                   1707:     my %servers = &get_servers($udom,'library');
                   1708:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1709:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1710: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1711: 
                   1712: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1713: 	if ($answer eq 'found') {
                   1714: 	    delete($badServerCache{$tryserver}); 
                   1715: 	    return $homecache{$index}=$tryserver;
                   1716: 	} elsif ($answer eq 'no_host') {
                   1717: 	    $badServerCache{$tryserver}=1;
                   1718: 	}
1.1       albertel 1719:     }    
                   1720:     return 'no_host';
1.70      www      1721: }
                   1722: 
                   1723: # ------------------------------------- Find the usernames behind a list of IDs
                   1724: 
                   1725: sub idget {
                   1726:     my ($udom,@ids)=@_;
                   1727:     my %returnhash=();
                   1728:     
1.841     albertel 1729:     my %servers = &get_servers($udom,'library');
                   1730:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1731: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1732: 	$idlist=~tr/A-Z/a-z/; 
                   1733: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1734: 	my @answer=();
                   1735: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1736: 	    @answer=split(/\&/,$reply);
                   1737: 	}                    ;
                   1738: 	my $i;
                   1739: 	for ($i=0;$i<=$#ids;$i++) {
                   1740: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1741: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1742: 	    } 
                   1743: 	}
                   1744:     } 
1.70      www      1745:     return %returnhash;
                   1746: }
                   1747: 
                   1748: # ------------------------------------- Find the IDs behind a list of usernames
                   1749: 
                   1750: sub idrget {
                   1751:     my ($udom,@unames)=@_;
                   1752:     my %returnhash=();
1.800     albertel 1753:     foreach my $uname (@unames) {
                   1754:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1755:     }
1.70      www      1756:     return %returnhash;
                   1757: }
                   1758: 
                   1759: # ------------------------------- Store away a list of names and associated IDs
                   1760: 
                   1761: sub idput {
                   1762:     my ($udom,%ids)=@_;
                   1763:     my %servers=();
1.800     albertel 1764:     foreach my $uname (keys(%ids)) {
                   1765: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1766:         my $uhom=&homeserver($uname,$udom);
1.70      www      1767:         if ($uhom ne 'no_host') {
1.800     albertel 1768:             my $id=&escape($ids{$uname});
1.70      www      1769:             $id=~tr/A-Z/a-z/;
1.800     albertel 1770:             my $esc_unam=&escape($uname);
1.70      www      1771: 	    if ($servers{$uhom}) {
1.800     albertel 1772: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1773:             } else {
1.800     albertel 1774:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1775:             }
                   1776:         }
1.191     harris41 1777:     }
1.800     albertel 1778:     foreach my $server (keys(%servers)) {
                   1779:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1780:     }
1.344     www      1781: }
                   1782: 
1.1172.2.30  raeburn  1783: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1784: 
                   1785: sub iddel {
                   1786:     my ($udom,$idshashref,$uhome)=@_;
                   1787:     my %result=();
                   1788:     unless (ref($idshashref) eq 'HASH') {
                   1789:         return %result;
                   1790:     }
                   1791:     my %servers=();
                   1792:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1793:         my $uhom;
                   1794:         if ($uhome) {
                   1795:             $uhom = $uhome;
                   1796:         } else {
                   1797:             $uhom=&homeserver($uname,$udom);
                   1798:         }
                   1799:         if ($uhom ne 'no_host') {
                   1800:             if ($servers{$uhom}) {
                   1801:                 $servers{$uhom}.='&'.&escape($id);
                   1802:             } else {
                   1803:                 $servers{$uhom}=&escape($id);
                   1804:             }
                   1805:         }
                   1806:     }
                   1807:     foreach my $server (keys(%servers)) {
                   1808:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1809:     }
                   1810:     return %result;
                   1811: }
                   1812: 
1.1023    raeburn  1813: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1814: sub dump_dom {
1.1165    droeschl 1815:     my ($namespace, $udom, $regexp) = @_;
                   1816: 
                   1817:     $udom ||= $env{'user.domain'};
                   1818: 
                   1819:     return () unless $udom;
                   1820: 
                   1821:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1822: }
                   1823: 
1.1023    raeburn  1824: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1825: 
                   1826: sub get_dom {
1.860     raeburn  1827:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1828:     return if ($udom eq 'public');
1.806     raeburn  1829:     my $items='';
                   1830:     foreach my $item (@$storearr) {
                   1831:         $items.=&escape($item).'&';
                   1832:     }
                   1833:     $items=~s/\&$//;
1.860     raeburn  1834:     if (!$udom) {
                   1835:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1836:         return if ($udom eq 'public');
1.860     raeburn  1837:         if (defined(&domain($udom,'primary'))) {
                   1838:             $uhome=&domain($udom,'primary');
                   1839:         } else {
1.874     albertel 1840:             undef($uhome);
1.860     raeburn  1841:         }
                   1842:     } else {
                   1843:         if (!$uhome) {
                   1844:             if (defined(&domain($udom,'primary'))) {
                   1845:                 $uhome=&domain($udom,'primary');
                   1846:             }
                   1847:         }
                   1848:     }
                   1849:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1850:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1851:         my %returnhash;
1.875     albertel 1852:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1853:             return %returnhash;
                   1854:         }
1.806     raeburn  1855:         my @pairs=split(/\&/,$rep);
                   1856:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1857:             return @pairs;
                   1858:         }
                   1859:         my $i=0;
                   1860:         foreach my $item (@$storearr) {
                   1861:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1862:             $i++;
                   1863:         }
                   1864:         return %returnhash;
                   1865:     } else {
1.880     banghart 1866:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1867:     }
                   1868: }
                   1869: 
                   1870: # -------------------------------------------- put items in domain db files 
                   1871: 
                   1872: sub put_dom {
1.860     raeburn  1873:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1874:     if (!$udom) {
                   1875:         $udom=$env{'user.domain'};
                   1876:         if (defined(&domain($udom,'primary'))) {
                   1877:             $uhome=&domain($udom,'primary');
                   1878:         } else {
1.874     albertel 1879:             undef($uhome);
1.860     raeburn  1880:         }
                   1881:     } else {
                   1882:         if (!$uhome) {
                   1883:             if (defined(&domain($udom,'primary'))) {
                   1884:                 $uhome=&domain($udom,'primary');
                   1885:             }
                   1886:         }
                   1887:     } 
                   1888:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1889:         my $items='';
                   1890:         foreach my $item (keys(%$storehash)) {
                   1891:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1892:         }
                   1893:         $items=~s/\&$//;
                   1894:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1895:     } else {
1.860     raeburn  1896:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1897:     }
                   1898: }
                   1899: 
1.1023    raeburn  1900: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1901: sub newput_dom {
1.1023    raeburn  1902:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1903:     my $result;
                   1904:     if (!$udom) {
                   1905:         $udom=$env{'user.domain'};
                   1906:     }
1.1023    raeburn  1907:     if ($udom) {
                   1908:         my $uname = &get_domainconfiguser($udom);
                   1909:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1910:     }
                   1911:     return $result;
                   1912: }
                   1913: 
1.1023    raeburn  1914: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1915: sub del_dom {
1.1023    raeburn  1916:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1917:     if (ref($storearr) eq 'ARRAY') {
                   1918:         if (!$udom) {
                   1919:             $udom=$env{'user.domain'};
                   1920:         }
1.1023    raeburn  1921:         if ($udom) {
                   1922:             my $uname = &get_domainconfiguser($udom); 
                   1923:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1924:         }
                   1925:     }
                   1926: }
                   1927: 
1.1023    raeburn  1928: # ----------------------------------construct domainconfig user for a domain 
                   1929: sub get_domainconfiguser {
                   1930:     my ($udom) = @_;
                   1931:     return $udom.'-domainconfig';
                   1932: }
                   1933: 
1.837     raeburn  1934: sub retrieve_inst_usertypes {
                   1935:     my ($udom) = @_;
                   1936:     my (%returnhash,@order);
1.989     raeburn  1937:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1938:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1939:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1940:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1941:     } else {
                   1942:         if (defined(&domain($udom,'primary'))) {
                   1943:             my $uhome=&domain($udom,'primary');
                   1944:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1945:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1946:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1947:                 return (\%returnhash,\@order);
                   1948:             }
                   1949:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1950:             my @pairs=split(/\&/,$hashitems);
                   1951:             foreach my $item (@pairs) {
                   1952:                 my ($key,$value)=split(/=/,$item,2);
                   1953:                 $key = &unescape($key);
                   1954:                 next if ($key =~ /^error: 2 /);
                   1955:                 $returnhash{$key}=&thaw_unescape($value);
                   1956:             }
                   1957:             my @esc_order = split(/\&/,$orderitems);
                   1958:             foreach my $item (@esc_order) {
                   1959:                 push(@order,&unescape($item));
                   1960:             }
                   1961:         } else {
1.1172.2.44  raeburn  1962:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1963:         }
1.1172.2.44  raeburn  1964:         return (\%returnhash,\@order);
1.837     raeburn  1965:     }
                   1966: }
                   1967: 
1.868     raeburn  1968: sub is_domainimage {
                   1969:     my ($url) = @_;
1.1172.2.74  raeburn  1970:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1971:         if (&domain($1) ne '') {
                   1972:             return '1';
                   1973:         }
                   1974:     }
                   1975:     return;
                   1976: }
                   1977: 
1.899     raeburn  1978: sub inst_directory_query {
                   1979:     my ($srch) = @_;
                   1980:     my $udom = $srch->{'srchdomain'};
                   1981:     my %results;
                   1982:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1983:     my $outcome;
1.899     raeburn  1984:     if ($homeserver ne '') {
1.904     albertel 1985: 	my $queryid=&reply("querysend:instdirsearch:".
                   1986: 			   &escape($srch->{'srchby'}).':'.
                   1987: 			   &escape($srch->{'srchterm'}).':'.
                   1988: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1989: 	my $host=&hostname($homeserver);
                   1990: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1991: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1992: 	    return;
                   1993: 	}
                   1994: 	my $response = &get_query_reply($queryid);
                   1995: 	my $maxtries = 5;
                   1996: 	my $tries = 1;
                   1997: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1998: 	    $response = &get_query_reply($queryid);
                   1999: 	    $tries ++;
                   2000: 	}
                   2001: 
                   2002:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2003:             if ($response eq 'unavailable') {
                   2004:                 $outcome = $response;
                   2005:             } else {
                   2006:                 $outcome = 'ok';
                   2007:                 my @matches = split(/\n/,$response);
                   2008:                 foreach my $match (@matches) {
                   2009:                     my ($key,$value) = split(/=/,$match);
                   2010:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2011:                 }
1.899     raeburn  2012:             }
                   2013:         }
                   2014:     }
1.909     raeburn  2015:     return ($outcome,%results);
1.899     raeburn  2016: }
                   2017: 
                   2018: sub usersearch {
                   2019:     my ($srch) = @_;
                   2020:     my $dom = $srch->{'srchdomain'};
                   2021:     my %results;
                   2022:     my %libserv = &all_library();
                   2023:     my $query = 'usersearch';
                   2024:     foreach my $tryserver (keys(%libserv)) {
                   2025:         if (&host_domain($tryserver) eq $dom) {
                   2026:             my $host=&hostname($tryserver);
                   2027:             my $queryid=
1.911     raeburn  2028:                 &reply("querysend:".&escape($query).':'.
                   2029:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2030:                        &escape($srch->{'srchtype'}).':'.
                   2031:                        &escape($srch->{'srchterm'}),$tryserver);
                   2032:             if ($queryid !~/^\Q$host\E\_/) {
                   2033:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2034:                 next;
1.899     raeburn  2035:             }
                   2036:             my $reply = &get_query_reply($queryid);
                   2037:             my $maxtries = 1;
                   2038:             my $tries = 1;
                   2039:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2040:                 $reply = &get_query_reply($queryid);
                   2041:                 $tries ++;
                   2042:             }
                   2043:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2044:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2045:             } else {
1.911     raeburn  2046:                 my @matches;
                   2047:                 if ($reply =~ /\n/) {
                   2048:                     @matches = split(/\n/,$reply);
                   2049:                 } else {
                   2050:                     @matches = split(/\&/,$reply);
                   2051:                 }
1.899     raeburn  2052:                 foreach my $match (@matches) {
                   2053:                     my ($uname,$udom,%userhash);
1.911     raeburn  2054:                     foreach my $entry (split(/:/,$match)) {
                   2055:                         my ($key,$value) =
                   2056:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2057:                         $userhash{$key} = $value;
                   2058:                         if ($key eq 'username') {
                   2059:                             $uname = $value;
                   2060:                         } elsif ($key eq 'domain') {
                   2061:                             $udom = $value;
1.911     raeburn  2062:                         }
1.899     raeburn  2063:                     }
                   2064:                     $results{$uname.':'.$udom} = \%userhash;
                   2065:                 }
                   2066:             }
                   2067:         }
                   2068:     }
                   2069:     return %results;
                   2070: }
                   2071: 
1.912     raeburn  2072: sub get_instuser {
                   2073:     my ($udom,$uname,$id) = @_;
                   2074:     my $homeserver = &domain($udom,'primary');
                   2075:     my ($outcome,%results);
                   2076:     if ($homeserver ne '') {
                   2077:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2078:                            &escape($id).':'.&escape($udom),$homeserver);
                   2079:         my $host=&hostname($homeserver);
                   2080:         if ($queryid !~/^\Q$host\E\_/) {
                   2081:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2082:             return;
                   2083:         }
                   2084:         my $response = &get_query_reply($queryid);
                   2085:         my $maxtries = 5;
                   2086:         my $tries = 1;
                   2087:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2088:             $response = &get_query_reply($queryid);
                   2089:             $tries ++;
                   2090:         }
                   2091:         if (!&error($response) && $response ne 'refused') {
                   2092:             if ($response eq 'unavailable') {
                   2093:                 $outcome = $response;
                   2094:             } else {
                   2095:                 $outcome = 'ok';
                   2096:                 my @matches = split(/\n/,$response);
                   2097:                 foreach my $match (@matches) {
                   2098:                     my ($key,$value) = split(/=/,$match);
                   2099:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2100:                 }
                   2101:             }
                   2102:         }
                   2103:     }
                   2104:     my %userinfo;
                   2105:     if (ref($results{$uname}) eq 'HASH') {
                   2106:         %userinfo = %{$results{$uname}};
                   2107:     } 
                   2108:     return ($outcome,%userinfo);
                   2109: }
                   2110: 
1.1172.2.69  raeburn  2111: sub get_multiple_instusers {
                   2112:     my ($udom,$users,$caller) = @_;
                   2113:     my ($outcome,$results);
                   2114:     if (ref($users) eq 'HASH') {
                   2115:         my $count = keys(%{$users});
                   2116:         my $requested = &freeze_escape($users);
                   2117:         my $homeserver = &domain($udom,'primary');
                   2118:         if ($homeserver ne '') {
                   2119:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2120:             my $host=&hostname($homeserver);
                   2121:             if ($queryid !~/^\Q$host\E\_/) {
                   2122:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2123:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2124:                 return ($outcome,$results);
                   2125:             }
                   2126:             my $response = &get_query_reply($queryid);
                   2127:             my $maxtries = 5;
                   2128:             if ($count > 100) {
                   2129:                 $maxtries = 1+int($count/20);
                   2130:             }
                   2131:             my $tries = 1;
                   2132:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2133:                 $response = &get_query_reply($queryid);
                   2134:                 $tries ++;
                   2135:             }
                   2136:             if ($response eq '') {
                   2137:                 $results = {};
                   2138:                 foreach my $key (keys(%{$users})) {
                   2139:                     my ($uname,$id);
                   2140:                     if ($caller eq 'id') {
                   2141:                         $id = $key;
                   2142:                     } else {
                   2143:                         $uname = $key;
                   2144:                     }
                   2145:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2146:                     $outcome = $resp;
                   2147:                     if ($resp eq 'ok') {
                   2148:                         %{$results} = (%{$results}, %info);
                   2149:                     } else {
                   2150:                         last;
                   2151:                     }
                   2152:                 }
                   2153:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2154:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2155:                     $outcome = $response;
                   2156:                 } else {
                   2157:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2158:                     if ($outcome eq 'ok') {
                   2159:                         $results = &thaw_unescape($userdata);
                   2160:                     }
                   2161:                 }
                   2162:             }
                   2163:         }
                   2164:     }
                   2165:     return ($outcome,$results);
                   2166: }
                   2167: 
1.912     raeburn  2168: sub inst_rulecheck {
1.923     raeburn  2169:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2170:     my %returnhash;
                   2171:     if ($udom ne '') {
                   2172:         if (ref($rules) eq 'ARRAY') {
                   2173:             @{$rules} = map {&escape($_);} (@{$rules});
                   2174:             my $rulestr = join(':',@{$rules});
                   2175:             my $homeserver=&domain($udom,'primary');
                   2176:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2177:                 my $response;
                   2178:                 if ($item eq 'username') {                
                   2179:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2180:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2181:                                               $homeserver));
1.923     raeburn  2182:                 } elsif ($item eq 'id') {
                   2183:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2184:                                               ':'.&escape($id).':'.$rulestr,
                   2185:                                               $homeserver));
1.945     raeburn  2186:                 } elsif ($item eq 'selfcreate') {
                   2187:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2188:                                                &escape($udom).':'.&escape($uname).
                   2189:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2190:                 }
1.912     raeburn  2191:                 if ($response ne 'refused') {
                   2192:                     my @pairs=split(/\&/,$response);
                   2193:                     foreach my $item (@pairs) {
                   2194:                         my ($key,$value)=split(/=/,$item,2);
                   2195:                         $key = &unescape($key);
                   2196:                         next if ($key =~ /^error: 2 /);
                   2197:                         $returnhash{$key}=&thaw_unescape($value);
                   2198:                     }
                   2199:                 }
                   2200:             }
                   2201:         }
                   2202:     }
                   2203:     return %returnhash;
                   2204: }
                   2205: 
                   2206: sub inst_userrules {
1.923     raeburn  2207:     my ($udom,$check) = @_;
1.912     raeburn  2208:     my (%ruleshash,@ruleorder);
                   2209:     if ($udom ne '') {
                   2210:         my $homeserver=&domain($udom,'primary');
                   2211:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2212:             my $response;
                   2213:             if ($check eq 'id') {
                   2214:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2215:                                  $homeserver);
1.943     raeburn  2216:             } elsif ($check eq 'email') {
                   2217:                 $response=&reply('instemailrules:'.&escape($udom),
                   2218:                                  $homeserver);
1.923     raeburn  2219:             } else {
                   2220:                 $response=&reply('instuserrules:'.&escape($udom),
                   2221:                                  $homeserver);
                   2222:             }
1.912     raeburn  2223:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2224:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2225:                 ($response ne 'no_such_host')) {
                   2226:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2227:                 my @pairs=split(/\&/,$hashitems);
                   2228:                 foreach my $item (@pairs) {
                   2229:                     my ($key,$value)=split(/=/,$item,2);
                   2230:                     $key = &unescape($key);
                   2231:                     next if ($key =~ /^error: 2 /);
                   2232:                     $ruleshash{$key}=&thaw_unescape($value);
                   2233:                 }
                   2234:                 my @esc_order = split(/\&/,$orderitems);
                   2235:                 foreach my $item (@esc_order) {
                   2236:                     push(@ruleorder,&unescape($item));
                   2237:                 }
                   2238:             }
                   2239:         }
                   2240:     }
                   2241:     return (\%ruleshash,\@ruleorder);
                   2242: }
                   2243: 
1.976     raeburn  2244: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2245: 
                   2246: sub get_domain_defaults {
1.1172.2.35  raeburn  2247:     my ($domain,$ignore_cache) = @_;
                   2248:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2249:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2250:     unless ($ignore_cache) {
                   2251:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2252:         if (defined($cached)) {
                   2253:             if (ref($result) eq 'HASH') {
                   2254:                 return %{$result};
                   2255:             }
1.943     raeburn  2256:         }
                   2257:     }
                   2258:     my %domdefaults;
                   2259:     my %domconfig =
1.989     raeburn  2260:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2261:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2262:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2263:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2264:                                   'coursecategories','autoenroll',
                   2265:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2266:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2267:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2268:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2269:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2270:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2271:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2272:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2273:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2274:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2275:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2276:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2277:     } else {
                   2278:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2279:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2280:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2281:     }
1.976     raeburn  2282:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2283:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2284:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2285:         } else {
                   2286:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2287:         }
1.1172.2.6  raeburn  2288:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2289:         foreach my $item (@usertools) {
                   2290:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2291:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2292:             }
                   2293:         }
1.1172.2.29  raeburn  2294:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2295:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2296:         }
1.976     raeburn  2297:     }
1.985     raeburn  2298:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2299:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2300:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2301:         }
                   2302:     }
1.1172.2.9  raeburn  2303:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2304:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2305:     }
1.989     raeburn  2306:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2307:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2308:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2309:         }
                   2310:     }
1.1047    raeburn  2311:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2312:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2313:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2314:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2315:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2316:         }
1.1172.2.41  raeburn  2317:         foreach my $type (@coursetypes) {
                   2318:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2319:                 unless ($type eq 'community') {
                   2320:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2321:                 }
                   2322:             }
                   2323:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2324:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2325:             }
1.1172.2.60  raeburn  2326:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2327:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2328:                     $domdefaults{$type.'postsubtimeout'} =
                   2329:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2330:                 }
                   2331:             }
1.1172.2.30  raeburn  2332:         }
1.1172.2.67  raeburn  2333:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2334:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2335:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2336:                 if (@clonecodes) {
                   2337:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2338:                 }
                   2339:             }
                   2340:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2341:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2342:         }
1.1172.2.103  raeburn  2343:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2344:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2345:         }
1.1047    raeburn  2346:     }
1.1073    raeburn  2347:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2348:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2349:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2350:         }
                   2351:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2352:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2353:         }
1.1172.2.62  raeburn  2354:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2355:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2356:         }
1.1073    raeburn  2357:     }
1.1172.2.41  raeburn  2358:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2359:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2360:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2361:                             'approval','limit');
                   2362:             foreach my $type (@coursetypes) {
                   2363:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2364:                     my @mgrdc = ();
                   2365:                     foreach my $item (@settings) {
                   2366:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2367:                             push(@mgrdc,$item);
                   2368:                         }
                   2369:                     }
                   2370:                     if (@mgrdc) {
                   2371:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2372:                     }
                   2373:                 }
                   2374:             }
                   2375:         }
                   2376:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2377:             foreach my $type (@coursetypes) {
                   2378:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2379:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2380:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2381:                     }
                   2382:                 }
                   2383:             }
                   2384:         }
                   2385:     }
1.1172.2.46  raeburn  2386:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2387:         $domdefaults{'catauth'} = 'std';
                   2388:         $domdefaults{'catunauth'} = 'std';
                   2389:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2390:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2391:         }
                   2392:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2393:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2394:         }
                   2395:     }
1.1172.2.76  raeburn  2396:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2397:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2398:     }
1.1172.2.89  raeburn  2399:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2400:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2401:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2402:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2403:         }
                   2404:     }
1.1172.2.23  raeburn  2405:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2406:     return %domdefaults;
                   2407: }
                   2408: 
1.1172.2.106  raeburn  2409: sub get_dom_cats {
                   2410:     my ($dom) = @_;
                   2411:     return unless (&domain($dom));
                   2412:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2413:     unless (defined($cached)) {
                   2414:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2415:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2416:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2417:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2418:             } else {
                   2419:                 $cats = {};
                   2420:             }
                   2421:         } else {
                   2422:             $cats = {};
                   2423:         }
                   2424:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2425:     }
                   2426:     return $cats;
                   2427: }
                   2428: 
                   2429: sub get_dom_instcats {
                   2430:     my ($dom) = @_;
                   2431:     return unless (&domain($dom));
                   2432:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2433:     unless (defined($cached)) {
                   2434:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2435:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2436:         if ($totcodes > 0) {
                   2437:             my $caller = 'global';
                   2438:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2439:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2440:                 $instcats = {
                   2441:                                 codes => \%codes,
                   2442:                                 codetitles => \@codetitles,
                   2443:                                 cat_titles => \%cat_titles,
                   2444:                                 cat_order => \%cat_order,
                   2445:                             };
                   2446:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2447:             }
                   2448:         }
                   2449:     }
                   2450:     return $instcats;
                   2451: }
                   2452: 
                   2453: sub retrieve_instcodes {
                   2454:     my ($coursecodes,$dom) = @_;
                   2455:     my $totcodes;
                   2456:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2457:     foreach my $course (keys(%courses)) {
                   2458:         if (ref($courses{$course}) eq 'HASH') {
                   2459:             if ($courses{$course}{'inst_code'} ne '') {
                   2460:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2461:                 $totcodes ++;
                   2462:             }
                   2463:         }
                   2464:     }
                   2465:     return $totcodes;
                   2466: }
                   2467: 
1.344     www      2468: # --------------------------------------------------- Assign a key to a student
                   2469: 
                   2470: sub assign_access_key {
1.364     www      2471: #
                   2472: # a valid key looks like uname:udom#comments
                   2473: # comments are being appended
                   2474: #
1.498     www      2475:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2476:     $kdom=
1.620     albertel 2477:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2478:     $knum=
1.620     albertel 2479:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2480:     $cdom=
1.620     albertel 2481:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2482:     $cnum=
1.620     albertel 2483:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2484:     $udom=$env{'user.name'} unless (defined($udom));
                   2485:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2486:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2487:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2488:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2489:                                                   # assigned to this person
                   2490:                                                   # - this should not happen,
1.345     www      2491:                                                   # unless something went wrong
                   2492:                                                   # the first time around
                   2493: # ready to assign
1.364     www      2494:         $logentry=$1.'; '.$logentry;
1.496     www      2495:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2496:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2497: # key now belongs to user
1.346     www      2498: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2499:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2500:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2501:                 return 'ok';
                   2502:             } else {
                   2503:                 return 
                   2504:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2505: 	    }
                   2506:         } else {
                   2507:             return 'error: Could not assign key, try again later.';
                   2508:         }
1.364     www      2509:     } elsif (!$existing{$ckey}) {
1.345     www      2510: # the key does not exist
                   2511: 	return 'error: The key does not exist';
                   2512:     } else {
                   2513: # the key is somebody else's
                   2514: 	return 'error: The key is already in use';
                   2515:     }
1.344     www      2516: }
                   2517: 
1.364     www      2518: # ------------------------------------------ put an additional comment on a key
                   2519: 
                   2520: sub comment_access_key {
                   2521: #
                   2522: # a valid key looks like uname:udom#comments
                   2523: # comments are being appended
                   2524: #
                   2525:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2526:     $cdom=
1.620     albertel 2527:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2528:     $cnum=
1.620     albertel 2529:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2530:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2531:     if ($existing{$ckey}) {
                   2532:         $existing{$ckey}.='; '.$logentry;
                   2533: # ready to assign
1.367     www      2534:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2535:                                                  $cdom,$cnum) eq 'ok') {
                   2536: 	    return 'ok';
                   2537:         } else {
                   2538: 	    return 'error: Count not store comment.';
                   2539:         }
                   2540:     } else {
                   2541: # the key does not exist
                   2542: 	return 'error: The key does not exist';
                   2543:     }
                   2544: }
                   2545: 
1.344     www      2546: # ------------------------------------------------------ Generate a set of keys
                   2547: 
                   2548: sub generate_access_keys {
1.364     www      2549:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2550:     $cdom=
1.620     albertel 2551:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2552:     $cnum=
1.620     albertel 2553:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2554:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2555:     unless (($cdom) && ($cnum)) { return 0; }
                   2556:     if ($number>10000) { return 0; }
                   2557:     sleep(2); # make sure don't get same seed twice
                   2558:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2559:     my $total=0;
                   2560:     for (my $i=1;$i<=$number;$i++) {
                   2561:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2562:                   sprintf("%lx",int(100000*rand)).'-'.
                   2563:                   sprintf("%lx",int(100000*rand));
                   2564:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2565:        $newkey=~s/0/h/g; # and also 0 and O
                   2566:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2567:        if ($existing{$newkey}) {
                   2568:            $i--;
                   2569:        } else {
1.364     www      2570: 	  if (&put('accesskeys',
                   2571:               { $newkey => '# generated '.localtime().
1.620     albertel 2572:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2573:                            '; '.$logentry },
                   2574: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2575:               $total++;
                   2576: 	  }
                   2577:        }
                   2578:     }
1.620     albertel 2579:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2580:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2581:     return $total;
                   2582: }
                   2583: 
                   2584: # ------------------------------------------------------- Validate an accesskey
                   2585: 
                   2586: sub validate_access_key {
                   2587:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2588:     $cdom=
1.620     albertel 2589:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2590:     $cnum=
1.620     albertel 2591:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2592:     $udom=$env{'user.domain'} unless (defined($udom));
                   2593:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2594:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2595:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2596: }
                   2597: 
                   2598: # ------------------------------------- Find the section of student in a course
1.652     albertel 2599: sub devalidate_getsection_cache {
                   2600:     my ($udom,$unam,$courseid)=@_;
                   2601:     my $hashid="$udom:$unam:$courseid";
                   2602:     &devalidate_cache_new('getsection',$hashid);
                   2603: }
1.298     matthew  2604: 
1.815     albertel 2605: sub courseid_to_courseurl {
                   2606:     my ($courseid) = @_;
                   2607:     #already url style courseid
                   2608:     return $courseid if ($courseid =~ m{^/});
                   2609: 
                   2610:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2611: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2612: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2613: 	return "/$cdom/$cnum";
                   2614:     }
                   2615: 
                   2616:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2617:     if (exists($courseinfo{'num'})) {
                   2618: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2619:     }
                   2620: 
                   2621:     return undef;
                   2622: }
                   2623: 
1.298     matthew  2624: sub getsection {
                   2625:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2626:     my $cachetime=1800;
1.551     albertel 2627: 
                   2628:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2629:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2630:     if (defined($cached)) { return $result; }
                   2631: 
1.298     matthew  2632:     my %Pending; 
                   2633:     my %Expired;
                   2634:     #
                   2635:     # Each role can either have not started yet (pending), be active, 
                   2636:     #    or have expired.
                   2637:     #
                   2638:     # If there is an active role, we are done.
                   2639:     #
                   2640:     # If there is more than one role which has not started yet, 
                   2641:     #     choose the one which will start sooner
                   2642:     # If there is one role which has not started yet, return it.
                   2643:     #
                   2644:     # If there is more than one expired role, choose the one which ended last.
                   2645:     # If there is a role which has expired, return it.
                   2646:     #
1.815     albertel 2647:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2648:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2649:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2650:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2651:         my $section=$1;
                   2652:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2653:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2654:         my $now=time;
1.548     albertel 2655:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2656:             $Expired{$end}=$section;
                   2657:             next;
                   2658:         }
1.548     albertel 2659:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2660:             $Pending{$start}=$section;
                   2661:             next;
                   2662:         }
1.599     albertel 2663:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2664:     }
                   2665:     #
                   2666:     # Presumedly there will be few matching roles from the above
                   2667:     # loop and the sorting time will be negligible.
                   2668:     if (scalar(keys(%Pending))) {
                   2669:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2670:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2671:     } 
                   2672:     if (scalar(keys(%Expired))) {
                   2673:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2674:         my $time = pop(@sorted);
1.599     albertel 2675:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2676:     }
1.599     albertel 2677:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2678: }
1.70      www      2679: 
1.599     albertel 2680: sub save_cache {
                   2681:     &purge_remembered();
1.722     albertel 2682:     #&Apache::loncommon::validate_page();
1.620     albertel 2683:     undef(%env);
1.780     albertel 2684:     undef($env_loaded);
1.599     albertel 2685: }
1.452     albertel 2686: 
1.599     albertel 2687: my $to_remember=-1;
                   2688: my %remembered;
                   2689: my %accessed;
                   2690: my $kicks=0;
                   2691: my $hits=0;
1.849     albertel 2692: sub make_key {
                   2693:     my ($name,$id) = @_;
1.872     albertel 2694:     if (length($id) > 65 
                   2695: 	&& length(&escape($id)) > 200) {
                   2696: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2697:     }
1.849     albertel 2698:     return &escape($name.':'.$id);
                   2699: }
                   2700: 
1.599     albertel 2701: sub devalidate_cache_new {
                   2702:     my ($name,$id,$debug) = @_;
                   2703:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2704:     my $remembered_id=$name.':'.$id;
1.849     albertel 2705:     $id=&make_key($name,$id);
1.599     albertel 2706:     $memcache->delete($id);
1.1172.2.81  raeburn  2707:     delete($remembered{$remembered_id});
                   2708:     delete($accessed{$remembered_id});
1.599     albertel 2709: }
                   2710: 
                   2711: sub is_cached_new {
                   2712:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2713:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2714:                                      # keys in %remembered hash, which persists for
                   2715:                                      # duration of request (no restriction on key length).
                   2716:     if (exists($remembered{$remembered_id})) {
                   2717: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2718: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2719: 	$hits++;
1.1172.2.81  raeburn  2720: 	return ($remembered{$remembered_id},1);
1.599     albertel 2721:     }
1.1172.2.81  raeburn  2722:     $id=&make_key($name,$id);
1.599     albertel 2723:     my $value = $memcache->get($id);
                   2724:     if (!(defined($value))) {
                   2725: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2726: 	return (undef,undef);
1.416     albertel 2727:     }
1.599     albertel 2728:     if ($value eq '__undef__') {
                   2729: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2730: 	$value=undef;
                   2731:     }
1.1172.2.81  raeburn  2732:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2733:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2734:     return ($value,1);
                   2735: }
                   2736: 
                   2737: sub do_cache_new {
                   2738:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2739:     my $remembered_id=$name.':'.$id;
1.849     albertel 2740:     $id=&make_key($name,$id);
1.599     albertel 2741:     my $setvalue=$value;
                   2742:     if (!defined($setvalue)) {
                   2743: 	$setvalue='__undef__';
                   2744:     }
1.623     albertel 2745:     if (!defined($time) ) {
                   2746: 	$time=600;
                   2747:     }
1.599     albertel 2748:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2749:     my $result = $memcache->set($id,$setvalue,$time);
                   2750:     if (! $result) {
1.872     albertel 2751: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2752: 	$memcache->disconnect_all();
1.872     albertel 2753:     }
1.600     albertel 2754:     # need to make a copy of $value
1.1172.2.81  raeburn  2755:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2756:     return $value;
                   2757: }
                   2758: 
                   2759: sub make_room {
1.1172.2.81  raeburn  2760:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2761: 
1.1172.2.81  raeburn  2762:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2763:                                     : $value;
1.599     albertel 2764:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2765:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2766:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2767:     my $to_kick;
                   2768:     my $max_time=0;
                   2769:     foreach my $other (keys(%accessed)) {
                   2770: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2771: 	    $to_kick=$other;
                   2772: 	    $max_time=&tv_interval($accessed{$other});
                   2773: 	}
                   2774:     }
                   2775:     delete($remembered{$to_kick});
                   2776:     delete($accessed{$to_kick});
                   2777:     $kicks++;
                   2778:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2779:     return;
                   2780: }
                   2781: 
1.599     albertel 2782: sub purge_remembered {
1.604     albertel 2783:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2784:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2785:     undef(%remembered);
                   2786:     undef(%accessed);
1.428     albertel 2787: }
1.70      www      2788: # ------------------------------------- Read an entry from a user's environment
                   2789: 
                   2790: sub userenvironment {
                   2791:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2792:     my $items;
                   2793:     foreach my $item (@what) {
                   2794:         $items.=&escape($item).'&';
                   2795:     }
                   2796:     $items=~s/\&$//;
1.70      www      2797:     my %returnhash=();
1.1009    raeburn  2798:     my $uhome = &homeserver($unam,$udom);
                   2799:     unless ($uhome eq 'no_host') {
                   2800:         my @answer=split(/\&/, 
                   2801:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2802:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2803:             return %returnhash;
                   2804:         }
1.1009    raeburn  2805:         my $i;
                   2806:         for ($i=0;$i<=$#what;$i++) {
                   2807: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2808:         }
1.70      www      2809:     }
                   2810:     return %returnhash;
1.1       albertel 2811: }
                   2812: 
1.617     albertel 2813: # ---------------------------------------------------------- Get a studentphoto
                   2814: sub studentphoto {
                   2815:     my ($udom,$unam,$ext) = @_;
                   2816:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2817:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2818:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2819:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2820:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2821:             } else {
                   2822:                 my ($result,$perm_reqd)=
1.707     albertel 2823: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2824:                 if ($result eq 'ok') {
                   2825:                     if (!($perm_reqd eq 'yes')) {
                   2826:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2827:                     }
                   2828:                 }
                   2829:             }
                   2830:         }
                   2831:     } else {
                   2832:         my ($result,$perm_reqd) = 
1.707     albertel 2833: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2834:         if ($result eq 'ok') {
                   2835:             if (!($perm_reqd eq 'yes')) {
                   2836:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2837:             }
                   2838:         }
                   2839:     }
                   2840:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2841: }
                   2842: 
                   2843: sub retrievestudentphoto {
                   2844:     my ($udom,$unam,$ext,$type) = @_;
                   2845:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2846:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2847:     if ($ret eq 'ok') {
                   2848:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2849:         if ($type eq 'thumbnail') {
                   2850:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2851:         }
                   2852:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2853:         return $tokenurl;
                   2854:     } else {
                   2855:         if ($type eq 'thumbnail') {
                   2856:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2857:         } else { 
                   2858:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2859:         }
1.617     albertel 2860:     }
                   2861: }
                   2862: 
1.263     www      2863: # -------------------------------------------------------------------- New chat
                   2864: 
                   2865: sub chatsend {
1.724     raeburn  2866:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2867:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2868:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2869:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2870:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2871: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2872: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2873: }
                   2874: 
                   2875: # ------------------------------------------ Find current version of a resource
                   2876: 
                   2877: sub getversion {
                   2878:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2879:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2880:     return &currentversion(&filelocation('',$fname));
                   2881: }
                   2882: 
                   2883: sub currentversion {
                   2884:     my $fname=shift;
                   2885:     my $author=$fname;
                   2886:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2887:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2888:     my $home=&homeserver($uname,$udom);
1.292     www      2889:     if ($home eq 'no_host') { 
                   2890:         return -1; 
                   2891:     }
1.1112    www      2892:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2893:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2894: 	return -1;
                   2895:     }
1.1112    www      2896:     return $answer;
1.263     www      2897: }
                   2898: 
1.1111    www      2899: #
                   2900: # Return special version number of resource if set by override, empty otherwise
                   2901: #
                   2902: sub usedversion {
                   2903:     my $fname=shift;
                   2904:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2905:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2906:     if ($urlversion) { return $urlversion; }
                   2907:     return '';
                   2908: }
                   2909: 
1.1       albertel 2910: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2911: 
1.1       albertel 2912: sub subscribe {
                   2913:     my $fname=shift;
1.761     raeburn  2914:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2915:     $fname=~s/[\n\r]//g;
1.1       albertel 2916:     my $author=$fname;
                   2917:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2918:     my ($udom,$uname)=split(/\//,$author);
                   2919:     my $home=homeserver($uname,$udom);
1.335     albertel 2920:     if ($home eq 'no_host') {
                   2921:         return 'not_found';
1.1       albertel 2922:     }
                   2923:     my $answer=reply("sub:$fname",$home);
1.64      www      2924:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2925: 	$answer.=' by '.$home;
                   2926:     }
1.1       albertel 2927:     return $answer;
                   2928: }
                   2929:     
1.8       www      2930: # -------------------------------------------------------------- Replicate file
                   2931: 
                   2932: sub repcopy {
                   2933:     my $filename=shift;
1.23      www      2934:     $filename=~s/\/+/\//g;
1.1142    raeburn  2935:     my $londocroot = $perlvar{'lonDocRoot'};
                   2936:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2937:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2938:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2939: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2940: 	return &repcopy_userfile($filename);
                   2941:     }
1.532     albertel 2942:     $filename=~s/[\n\r]//g;
1.8       www      2943:     my $transname="$filename.in.transfer";
1.828     www      2944: # FIXME: this should flock
1.607     raeburn  2945:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2946:     my $remoteurl=subscribe($filename);
1.64      www      2947:     if ($remoteurl =~ /^con_lost by/) {
                   2948: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2949:            return 'unavailable';
1.8       www      2950:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2951: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2952: 	   return 'not_found';
1.64      www      2953:     } elsif ($remoteurl =~ /^rejected by/) {
                   2954: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2955:            return 'forbidden';
1.20      www      2956:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2957:            return 'ok';
1.8       www      2958:     } else {
1.290     www      2959:         my $author=$filename;
                   2960:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2961:         my ($udom,$uname)=split(/\//,$author);
                   2962:         my $home=homeserver($uname,$udom);
                   2963:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2964:            my @parts=split(/\//,$filename);
                   2965:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2966:            if ($path ne "$londocroot/res") {
1.8       www      2967:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2968: 	       return 'bad_request';
1.8       www      2969:            }
                   2970:            my $count;
                   2971:            for ($count=5;$count<$#parts;$count++) {
                   2972:                $path.="/$parts[$count]";
                   2973:                if ((-e $path)!=1) {
                   2974: 		   mkdir($path,0777);
                   2975:                }
                   2976:            }
                   2977:            my $ua=new LWP::UserAgent;
                   2978:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2979:            my $response=$ua->request($request,$transname);
                   2980:            if ($response->is_error()) {
                   2981: 	       unlink($transname);
                   2982:                my $message=$response->status_line;
1.672     albertel 2983:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2984:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2985:                return 'unavailable';
1.8       www      2986:            } else {
1.16      www      2987: 	       if ($remoteurl!~/\.meta$/) {
                   2988:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2989:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2990:                   if ($mresponse->is_error()) {
                   2991: 		      unlink($filename.'.meta');
                   2992:                       &logthis(
1.672     albertel 2993:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2994:                   }
                   2995: 	       }
1.8       www      2996:                rename($transname,$filename);
1.607     raeburn  2997:                return 'ok';
1.8       www      2998:            }
1.290     www      2999:        }
1.8       www      3000:     }
1.330     www      3001: }
                   3002: 
                   3003: # ------------------------------------------------ Get server side include body
                   3004: sub ssi_body {
1.381     albertel 3005:     my ($filelink,%form)=@_;
1.606     matthew  3006:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3007:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3008:     }
1.953     www      3009:     my $output='';
                   3010:     my $response;
1.980     raeburn  3011:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3012:        ($output,$response)=&externalssi($filelink);
1.953     www      3013:     } else {
1.1004    droeschl 3014:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3015:        $filelink .= 'inhibitmenu=yes';
1.953     www      3016:        ($output,$response)=&ssi($filelink,%form);
                   3017:     }
1.778     albertel 3018:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3019:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3020:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3021:     if (wantarray) {
                   3022:         return ($output, $response);
                   3023:     } else {
                   3024:         return $output;
                   3025:     }
1.8       www      3026: }
                   3027: 
1.15      www      3028: # --------------------------------------------------------- Server Side Include
                   3029: 
1.782     albertel 3030: sub absolute_url {
                   3031:     my ($host_name) = @_;
                   3032:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3033:     if ($host_name eq '') {
                   3034: 	$host_name = $ENV{'SERVER_NAME'};
                   3035:     }
                   3036:     return $protocol.$host_name;
                   3037: }
                   3038: 
1.942     foxr     3039: #
                   3040: #   Server side include.
                   3041: # Parameters:
                   3042: #  fn     Possibly encrypted resource name/id.
                   3043: #  form   Hash that describes how the rendering should be done
                   3044: #         and other things.
1.944     foxr     3045: # Returns:
1.950     raeburn  3046: #   Scalar context: The content of the response.
                   3047: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3048: #     
1.15      www      3049: sub ssi {
                   3050: 
1.944     foxr     3051:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3052:     my ($request,$response);
1.711     albertel 3053: 
                   3054:     $form{'no_update_last_known'}=1;
1.895     albertel 3055:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3056:     if (%form) {
1.782     albertel 3057:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3058:       $request->content(join('&',map {
                   3059:             my $name = escape($_);
                   3060:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3061:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3062:             : &escape($form{$_}) );
                   3063:         } keys(%form)));
1.23      www      3064:     } else {
1.782     albertel 3065:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3066:     }
                   3067: 
1.15      www      3068:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3069: 
1.1172.2.101  raeburn  3070:     if (($env{'request.course.id'}) &&
                   3071:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3072:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3073:         ($form{'grade_symb'} ne '') &&
                   3074:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3075:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3076:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3077:             my $ua=new LWP::UserAgent;
                   3078:             $ua->local_address('127.0.0.1');
                   3079:             $response = $ua->request($request);
                   3080:         } else {
                   3081:             {
                   3082:                 require LWP::Protocol::http;
                   3083:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3084:                 my $ua=new LWP::UserAgent;
                   3085:                 $response = $ua->request($request);
                   3086:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3087:             }
                   3088:         }
                   3089:     } else {
                   3090:         my $ua=new LWP::UserAgent;
                   3091:         $response = $ua->request($request);
                   3092:     }
1.944     foxr     3093:     if (wantarray) {
1.1172.2.3  raeburn  3094: 	return ($response->content, $response);
1.944     foxr     3095:     } else {
1.1172.2.3  raeburn  3096: 	return $response->content;
1.942     foxr     3097:     }
1.324     www      3098: }
                   3099: 
                   3100: sub externalssi {
                   3101:     my ($url)=@_;
                   3102:     my $ua=new LWP::UserAgent;
                   3103:     my $request=new HTTP::Request('GET',$url);
                   3104:     my $response=$ua->request($request);
1.954     raeburn  3105:     if (wantarray) {
                   3106:         return ($response->content, $response);
                   3107:     } else {
                   3108:         return $response->content;
                   3109:     }
1.15      www      3110: }
1.254     www      3111: 
1.1172.2.98  raeburn  3112: # If the local copy of a replicated resource is outdated, trigger a
                   3113: # connection from the homeserver to flush the delayed queue. If no update
                   3114: # happens, remove local copies of outdated resource (and corresponding
                   3115: # metadata file).
                   3116: 
                   3117: sub remove_stale_resfile {
                   3118:     my ($url) = @_;
                   3119:     my $removed;
                   3120:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3121:         my $audom = $1;
                   3122:         my $auname = $2;
                   3123:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3124:             my $homeserver = &homeserver($auname,$audom);
                   3125:             unless (($homeserver eq 'no_host') ||
                   3126:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3127:                 my $fname = &filelocation('',$url);
                   3128:                 if (-e $fname) {
                   3129:                     my $ua=new LWP::UserAgent;
                   3130:                     $ua->timeout(5);
                   3131:                     my $protocol = $protocol{$homeserver};
                   3132:                     $protocol = 'http' if ($protocol ne 'https');
                   3133:                     my $hostname = &hostname($homeserver);
                   3134:                     if ($hostname) {
                   3135:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   3136:                         my $request=new HTTP::Request('HEAD',$uri);
                   3137:                         my $response=$ua->request($request);
                   3138:                         if ($response->is_success()) {
                   3139:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3140:                             my $locmodtime = (stat($fname))[9];
                   3141:                             if ($locmodtime < $remmodtime) {
                   3142:                                 my $stale;
                   3143:                                 my $answer = &reply('pong',$homeserver);
                   3144:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3145:                                     sleep(0.2);
                   3146:                                     $locmodtime = (stat($fname))[9];
                   3147:                                     if ($locmodtime < $remmodtime) {
                   3148:                                         my $posstransfer = $fname.'.in.transfer';
                   3149:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3150:                                             $removed = 1;
                   3151:                                         } else {
                   3152:                                             $stale = 1;
                   3153:                                         }
                   3154:                                     } else {
                   3155:                                         $removed = 1;
                   3156:                                     }
                   3157:                                 } else {
                   3158:                                     $stale = 1;
                   3159:                                 }
                   3160:                                 if ($stale) {
                   3161:                                     unlink($fname);
                   3162:                                     if ($uri!~/\.meta$/) {
                   3163:                                         unlink($fname.'.meta');
                   3164:                                     }
                   3165:                                     &reply("unsub:$fname",$homeserver);
                   3166:                                     $removed = 1;
                   3167:                                 }
                   3168:                             }
                   3169:                         }
                   3170:                     }
                   3171:                 }
                   3172:             }
                   3173:         }
                   3174:     }
                   3175:     return $removed;
                   3176: }
                   3177: 
1.492     albertel 3178: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3179: 
                   3180: sub allowuploaded {
                   3181:     my ($srcurl,$url)=@_;
                   3182:     $url=&clutter(&declutter($url));
                   3183:     my $dir=$url;
                   3184:     $dir=~s/\/[^\/]+$//;
                   3185:     my %httpref=();
                   3186:     my $httpurl=&hreflocation('',$url);
                   3187:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3188:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3189: }
1.477     raeburn  3190: 
1.1172.2.13  raeburn  3191: #
                   3192: # Determine if the current user should be able to edit a particular resource,
                   3193: # when viewing in course context.
                   3194: # (a) When viewing resource used to determine if "Edit" item is included in
                   3195: #     Functions.
                   3196: # (b) When displaying folder contents in course editor, used to determine if
                   3197: #     "Edit" link will be displayed alongside resource.
                   3198: #
                   3199: #  input: six args -- filename (decluttered), course number, course domain,
                   3200: #                   url, symb (if registered) and group (if this is a group
                   3201: #                   item -- e.g., bulletin board, group page etc.).
                   3202: #  output: array of five scalars --
                   3203: #          $cfile -- url for file editing if editable on current server
                   3204: #          $home -- homeserver of resource (i.e., for author if published,
                   3205: #                                           or course if uploaded.).
                   3206: #          $switchserver --  1 if server switch will be needed.
                   3207: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3208: #          $forceview -- 1 if icon/link should be to go to view mode
                   3209: #
                   3210: 
                   3211: sub can_edit_resource {
                   3212:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3213:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3214: #
                   3215: # For aboutme pages user can only edit his/her own.
                   3216: #
                   3217:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3218:         my ($sdom,$sname) = ($1,$2);
                   3219:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3220:             $home = $env{'user.home'};
                   3221:             $cfile = $resurl;
                   3222:             if ($env{'form.forceedit'}) {
                   3223:                 $forceview = 1;
                   3224:             } else {
                   3225:                 $forceedit = 1;
                   3226:             }
                   3227:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3228:         } else {
                   3229:             return;
                   3230:         }
                   3231:     }
                   3232: 
                   3233:     if ($env{'request.course.id'}) {
                   3234:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3235:         if ($group ne '') {
                   3236: # if this is a group homepage or group bulletin board, check group privs
                   3237:             my $allowed = 0;
                   3238:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3239:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3240:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3241:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3242:                     $allowed = 1;
                   3243:                 }
                   3244:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3245:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3246:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3247:                     $allowed = 1;
                   3248:                 }
                   3249:             }
                   3250:             if ($allowed) {
                   3251:                 $home=&homeserver($cnum,$cdom);
                   3252:                 if ($env{'form.forceedit'}) {
                   3253:                     $forceview = 1;
                   3254:                 } else {
                   3255:                     $forceedit = 1;
                   3256:                 }
                   3257:                 $cfile = $resurl;
                   3258:             } else {
                   3259:                 return;
                   3260:             }
                   3261:         } else {
1.1172.2.15  raeburn  3262:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3263:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3264:                     return;
                   3265:                 }
                   3266:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3267: #
                   3268: # No edit allowed where CC has switched to student role.
                   3269: #
                   3270:                 return;
                   3271:             }
                   3272:         }
                   3273:     }
                   3274: 
                   3275:     if ($file ne '') {
                   3276:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3277:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3278:                 $uploaded = 1;
                   3279:                 $incourse = 1;
                   3280:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3281:                     $cfile = &hreflocation('',$file);
                   3282:                     if ($env{'form.forceedit'}) {
                   3283:                         $forceview = 1;
                   3284:                     } else {
                   3285:                         $forceedit = 1;
                   3286:                     }
                   3287:                 }
                   3288:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3289:                 $incourse = 1;
                   3290:                 if ($env{'form.forceedit'}) {
                   3291:                     $forceview = 1;
                   3292:                 } else {
                   3293:                     $forceedit = 1;
                   3294:                 }
                   3295:                 $cfile = $resurl;
                   3296:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3297:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3298:                     $incourse = 1;
                   3299:                     if ($env{'form.forceedit'}) {
                   3300:                         $forceview = 1;
                   3301:                     } else {
                   3302:                         $forceedit = 1;
                   3303:                     }
                   3304:                     $cfile = $resurl;
                   3305:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3306:                     $incourse = 1;
                   3307:                     $cfile = $resurl.'/smpedit';
                   3308:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3309:                     $incourse = 1;
                   3310:                     if ($env{'form.forceedit'}) {
                   3311:                         $forceview = 1;
                   3312:                     } else {
                   3313:                         $forceedit = 1;
                   3314:                     }
                   3315:                     $cfile = $resurl;
1.1172.2.15  raeburn  3316:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3317:                     $incourse = 1;
                   3318:                     if ($env{'form.forceedit'}) {
                   3319:                         $forceview = 1;
                   3320:                     } else {
                   3321:                         $forceedit = 1;
                   3322:                     }
                   3323:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3324:                 }
                   3325:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3326:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3327:                 if (&is_on_map($template)) {
                   3328:                     $incourse = 1;
                   3329:                     $forceview = 1;
                   3330:                     $cfile = $template;
                   3331:                 }
                   3332:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3333:                     $incourse = 1;
                   3334:                     if ($env{'form.forceedit'}) {
                   3335:                         $forceview = 1;
                   3336:                     } else {
                   3337:                         $forceedit = 1;
                   3338:                     }
                   3339:                     $cfile = $resurl;
                   3340:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3341:                 $incourse = 1;
                   3342:                 $forceview = 1;
                   3343:                 if ($symb) {
                   3344:                     my ($map,$id,$res)=&decode_symb($symb);
                   3345:                     $env{'request.symb'} = $symb;
                   3346:                     $cfile = &clutter($res);
                   3347:                 } else {
                   3348:                     $cfile = $env{'form.suppurl'};
                   3349:                     $cfile =~ s{^http://}{};
                   3350:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3351:                 }
1.1172.2.31  raeburn  3352:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3353:                 if ($env{'form.forceedit'}) {
                   3354:                     $forceview = 1;
                   3355:                 } else {
                   3356:                     $forceedit = 1;
                   3357:                 }
                   3358:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3359:             }
                   3360:         }
                   3361:         if ($uploaded || $incourse) {
                   3362:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3363:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3364:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3365:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3366:             # Check that the user has permission to edit this resource
                   3367:             my $setpriv = 1;
                   3368:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3369:             if (defined($cfudom)) {
                   3370:                 $home=&homeserver($cfuname,$cfudom);
                   3371:                 $cfile=$file;
                   3372:             }
                   3373:         }
                   3374:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3375:             (($home ne '') && ($home ne 'no_host'))) {
                   3376:             my @ids=&current_machine_ids();
                   3377:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3378:                 $switchserver=1;
                   3379:             }
                   3380:         }
                   3381:     }
                   3382:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3383: }
                   3384: 
                   3385: sub is_course_upload {
                   3386:     my ($file,$cnum,$cdom) = @_;
                   3387:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3388:     $uploadpath =~ s{^\/}{};
                   3389:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3390:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3391:         return 1;
                   3392:     }
                   3393:     return;
                   3394: }
                   3395: 
                   3396: sub in_course {
                   3397:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3398:     if ($hideprivileged) {
                   3399:         my $skipuser;
1.1172.2.23  raeburn  3400:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3401:         my @possdoms = ($cdom);
                   3402:         if ($coursehash{'checkforpriv'}) {
                   3403:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3404:         }
                   3405:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3406:             $skipuser = 1;
                   3407:             if ($coursehash{'nothideprivileged'}) {
                   3408:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3409:                     my $user;
                   3410:                     if ($item =~ /:/) {
                   3411:                         $user = $item;
                   3412:                     } else {
                   3413:                         $user = join(':',split(/[\@]/,$item));
                   3414:                     }
                   3415:                     if ($user eq $uname.':'.$udom) {
                   3416:                         undef($skipuser);
                   3417:                         last;
                   3418:                     }
                   3419:                 }
                   3420:             }
                   3421:             if ($skipuser) {
                   3422:                 return 0;
                   3423:             }
                   3424:         }
                   3425:     }
                   3426:     $type ||= 'any';
                   3427:     if (!defined($cdom) || !defined($cnum)) {
                   3428:         my $cid  = $env{'request.course.id'};
                   3429:         $cdom = $env{'course.'.$cid.'.domain'};
                   3430:         $cnum = $env{'course.'.$cid.'.num'};
                   3431:     }
                   3432:     my $typesref;
                   3433:     if (($type eq 'any') || ($type eq 'all')) {
                   3434:         $typesref = ['active','previous','future'];
                   3435:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3436:         $typesref = [$type];
                   3437:     }
                   3438:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3439:                               $typesref,undef,[$cdom]);
                   3440:     my ($tmp) = keys(%roles);
                   3441:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3442:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3443:     if (@course_roles > 0) {
                   3444:         return 1;
                   3445:     }
                   3446:     return 0;
                   3447: }
                   3448: 
1.478     albertel 3449: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3450: # input: action, courseID, current domain, intended
1.637     raeburn  3451: #        path to file, source of file, instruction to parse file for objects,
                   3452: #        ref to hash for embedded objects,
                   3453: #        ref to hash for codebase of java objects.
1.1095    raeburn  3454: #        reference to scalar to accommodate mime type determined
                   3455: #          from File::MMagic if $parser = parse.
1.637     raeburn  3456: #
1.485     raeburn  3457: # output: url to file (if action was uploaddoc), 
                   3458: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3459: #
1.478     albertel 3460: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3461: # course.
1.477     raeburn  3462: #
1.478     albertel 3463: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3464: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3465: #          course's home server.
1.477     raeburn  3466: #
1.478     albertel 3467: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3468: #          be copied from $source (current location) to 
                   3469: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3470: #         and will then be copied to
                   3471: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3472: #         course's home server.
1.485     raeburn  3473: #
1.481     raeburn  3474: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3475: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3476: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3477: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3478: #         in course's home server.
1.637     raeburn  3479: #
1.477     raeburn  3480: 
                   3481: sub process_coursefile {
1.1095    raeburn  3482:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3483:         $mimetype)=@_;
1.477     raeburn  3484:     my $fetchresult;
1.638     albertel 3485:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3486:     if ($action eq 'propagate') {
1.638     albertel 3487:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3488: 			     $home);
1.481     raeburn  3489:     } else {
1.477     raeburn  3490:         my $fpath = '';
                   3491:         my $fname = $file;
1.478     albertel 3492:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3493:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3494:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3495:         if ($action eq 'copy') {
                   3496:             if ($source eq '') {
                   3497:                 $fetchresult = 'no source file';
                   3498:                 return $fetchresult;
                   3499:             } else {
                   3500:                 my $destination = $filepath.'/'.$fname;
                   3501:                 rename($source,$destination);
                   3502:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3503:                                  $home);
1.481     raeburn  3504:             }
                   3505:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3506:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3507:             print $fh $env{'form.'.$source};
1.481     raeburn  3508:             close($fh);
1.637     raeburn  3509:             if ($parser eq 'parse') {
1.1024    raeburn  3510:                 my $mm = new File::MMagic;
1.1095    raeburn  3511:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3512:                 if ($type eq 'text/html') {
1.1024    raeburn  3513:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3514:                     unless ($parse_result eq 'ok') {
                   3515:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3516:                     }
1.637     raeburn  3517:                 }
1.1095    raeburn  3518:                 if (ref($mimetype)) {
                   3519:                     $$mimetype = $type;
                   3520:                 } 
1.637     raeburn  3521:             }
1.477     raeburn  3522:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3523:                                  $home);
1.481     raeburn  3524:             if ($fetchresult eq 'ok') {
                   3525:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3526:             } else {
                   3527:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3528:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3529:                 return '/adm/notfound.html';
                   3530:             }
1.477     raeburn  3531:         }
                   3532:     }
1.485     raeburn  3533:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3534:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3535:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3536:     }
                   3537:     return $fetchresult;
                   3538: }
                   3539: 
1.637     raeburn  3540: sub build_filepath {
                   3541:     my ($fpath) = @_;
                   3542:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3543:     unless ($fpath eq '') {
                   3544:         my @parts=split('/',$fpath);
                   3545:         foreach my $part (@parts) {
                   3546:             $filepath.= '/'.$part;
                   3547:             if ((-e $filepath)!=1) {
                   3548:                 mkdir($filepath,0777);
                   3549:             }
                   3550:         }
                   3551:     }
                   3552:     return $filepath;
                   3553: }
                   3554: 
                   3555: sub store_edited_file {
1.638     albertel 3556:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3557:     my $file = $primary_url;
                   3558:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3559:     my $fpath = '';
                   3560:     my $fname = $file;
                   3561:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3562:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3563:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3564:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3565:     print $fh $content;
                   3566:     close($fh);
1.638     albertel 3567:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3568:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3569: 			  $home);
1.637     raeburn  3570:     if ($$fetchresult eq 'ok') {
                   3571:         return '/uploaded/'.$fpath.'/'.$fname;
                   3572:     } else {
1.638     albertel 3573:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3574: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3575:         return '/adm/notfound.html';
                   3576:     }
                   3577: }
                   3578: 
1.531     albertel 3579: sub clean_filename {
1.831     albertel 3580:     my ($fname,$args)=@_;
1.315     www      3581: # Replace Windows backslashes by forward slashes
1.257     www      3582:     $fname=~s/\\/\//g;
1.831     albertel 3583:     if (!$args->{'keep_path'}) {
                   3584:         # Get rid of everything but the actual filename
                   3585: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3586:     }
1.315     www      3587: # Replace spaces by underscores
                   3588:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3589: # Transliterate non-ascii text to ascii
                   3590:     my $lang = &Apache::lonlocal::current_language();
                   3591:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3592: # Replace all other weird characters by nothing
1.831     albertel 3593:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3594: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3595: # numbers
                   3596:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3597:     return $fname;
                   3598: }
1.1172.2.110  raeburn  3599: 
1.1051    raeburn  3600: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3601: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3602: # image with the same aspect ratio as the original, but with dimensions which do 
                   3603: # not exceed $resizewidth and $resizeheight.
                   3604:  
1.984     neumanie 3605: sub resizeImage {
1.1051    raeburn  3606:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3607:     my $ima = Image::Magick->new;
                   3608:     my $resized;
                   3609:     if (-e $img_path) {
                   3610:         $ima->Read($img_path);
                   3611:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3612:             my $width = $ima->Get('width');
                   3613:             my $height = $ima->Get('height');
                   3614:             if ($width > $resizewidth) {
                   3615: 	        my $factor = $width/$resizewidth;
                   3616:                 my $newheight = $height/$factor;
                   3617:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3618:                 $resized = 1;
                   3619:             }
                   3620:         }
                   3621:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3622:             my $width = $ima->Get('width');
                   3623:             my $height = $ima->Get('height');
                   3624:             if ($height > $resizeheight) {
                   3625:                 my $factor = $height/$resizeheight;
                   3626:                 my $newwidth = $width/$factor;
                   3627:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3628:                 $resized = 1;
                   3629:             }
                   3630:         }
                   3631:         if ($resized) {
                   3632:             $ima->Write($img_path);
                   3633:         }
                   3634:     }
                   3635:     return;
1.977     amueller 3636: }
                   3637: 
1.608     albertel 3638: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3639: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3640: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3641: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3642: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3643: #                   if 'coursedoc': upload to the current course
                   3644: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3645: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3646: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3647: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3648: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3649: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3650: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3651: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3652: #        $allfiles - reference to hash for embedded objects
                   3653: #        $codebase - reference to hash for codebase of java objects
                   3654: #        $desuname - username for permanent storage of uploaded file
                   3655: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3656: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3657: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3658: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3659: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3660: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3661: #                    from File::MMagic.
1.858     raeburn  3662: # 
1.686     albertel 3663: # output: url of file in userspace, or error: <message> 
                   3664: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3665: 
1.531     albertel 3666: sub userfileupload {
1.1090    raeburn  3667:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3668:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3669:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3670:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3671:     $fname=&clean_filename($fname);
1.1090    raeburn  3672:     # See if there is anything left
1.257     www      3673:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3674:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3675:     if ($fname =~ /^\./) {
                   3676:         my ($s,$usec) = &gettimeofday();
                   3677:         while (length($usec) < 6) {
                   3678:             $usec = '0'.$usec;
                   3679:         }
                   3680:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3681:     }
1.1090    raeburn  3682:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3683:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3684:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3685:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3686:         my $now = time;
1.1090    raeburn  3687:         my $filepath;
1.1095    raeburn  3688:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3689:              $filepath = 'tmp/helprequests/'.$now;
                   3690:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3691:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3692:                          '_'.$env{'user.domain'}.'/pending';
                   3693:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3694:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3695:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3696:                 $docudom = $destudom;
                   3697:             } else {
                   3698:                 $docudom = $env{'user.domain'};
                   3699:             }
1.1172.2.96  raeburn  3700:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3701:                 $docuname = $destuname;
                   3702:             } else {
                   3703:                 $docuname = $env{'user.name'};
                   3704:             }
                   3705:             if (exists($env{'form.group'})) {
                   3706:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3707:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3708:             }
                   3709:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3710:             if ($context eq 'canceloverwrite') {
                   3711:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3712:                 if (-e  $tempfile) {
                   3713:                     my @info = stat($tempfile);
                   3714:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3715:                         unlink($tempfile);
                   3716:                     }
                   3717:                 }
                   3718:                 return;
1.523     raeburn  3719:             }
                   3720:         }
1.1090    raeburn  3721:         # Create the directory if not present
1.741     raeburn  3722:         my @parts=split(/\//,$filepath);
                   3723:         my $fullpath = $perlvar{'lonDaemons'};
                   3724:         for (my $i=0;$i<@parts;$i++) {
                   3725:             $fullpath .= '/'.$parts[$i];
                   3726:             if ((-e $fullpath)!=1) {
                   3727:                 mkdir($fullpath,0777);
                   3728:             }
                   3729:         }
1.1172.2.96  raeburn  3730:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3731:         print $fh $env{'form.'.$formname};
                   3732:         close($fh);
1.1090    raeburn  3733:         if ($context eq 'existingfile') {
                   3734:             my @info = stat($fullpath.'/'.$fname);
                   3735:             return ($fullpath.'/'.$fname,$info[9]);
                   3736:         } else {
                   3737:             return $fullpath.'/'.$fname;
                   3738:         }
1.523     raeburn  3739:     }
1.995     raeburn  3740:     if ($subdir eq 'scantron') {
                   3741:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3742:     } else {
1.995     raeburn  3743:         $fname="$subdir/$fname";
                   3744:     }
1.1090    raeburn  3745:     if ($context eq 'coursedoc') {
1.638     albertel 3746: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3747: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3748:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3749:             return &finishuserfileupload($docuname,$docudom,
                   3750: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3751: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3752:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3753:         } else {
1.1172.2.21  raeburn  3754:             if ($env{'form.folder'}) {
                   3755:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3756:             }
1.638     albertel 3757:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3758: 				       $fname,$formname,$parser,
1.1095    raeburn  3759: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3760:         }
1.719     banghart 3761:     } elsif (defined($destuname)) {
                   3762:         my $docuname=$destuname;
                   3763:         my $docudom=$destudom;
1.860     raeburn  3764: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3765: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3766:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3767:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3768:     } else {
1.638     albertel 3769:         my $docuname=$env{'user.name'};
                   3770:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3771:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3772:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3773:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3774:         }
1.860     raeburn  3775: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3776: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3777:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3778:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3779:     }
1.271     www      3780: }
                   3781: 
                   3782: sub finishuserfileupload {
1.860     raeburn  3783:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3784:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3785:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3786:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3787:   
1.860     raeburn  3788:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3789:     $file=$fname;
                   3790:     if ($fname=~m|/|) {
                   3791:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3792: 	$path.=$fnamepath.'/';
                   3793:     }
1.259     www      3794:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3795:     my $count;
                   3796:     for ($count=4;$count<=$#parts;$count++) {
                   3797:         $filepath.="/$parts[$count]";
                   3798:         if ((-e $filepath)!=1) {
                   3799: 	    mkdir($filepath,0777);
                   3800:         }
                   3801:     }
1.984     neumanie 3802: 
1.258     www      3803: # Save the file
                   3804:     {
1.1172.2.96  raeburn  3805: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3806: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3807: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3808: 	    return '/adm/notfound.html';
                   3809: 	}
1.1090    raeburn  3810:         if ($context eq 'overwrite') {
1.1117    foxr     3811:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3812:             my $target = $filepath.'/'.$file;
                   3813:             if (-e $source) {
                   3814:                 my @info = stat($source);
                   3815:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3816:                     unless (&File::Copy::move($source,$target)) {
                   3817:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3818:                         return "Moving from $source failed";
                   3819:                     }
                   3820:                 } else {
                   3821:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3822:                 }
                   3823:             } else {
                   3824:                 return "Temporary file: $source missing";
                   3825:             }
                   3826:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3827: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3828: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3829: 	    return '/adm/notfound.html';
                   3830: 	}
1.570     albertel 3831: 	close(FH);
1.1051    raeburn  3832:         if ($resizewidth && $resizeheight) {
                   3833:             my $mm = new File::MMagic;
                   3834:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3835:             if ($mime_type =~ m{^image/}) {
                   3836: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3837:             }  
1.977     amueller 3838: 	}
1.258     www      3839:     }
1.1152    raeburn  3840:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3841:         if (ref($mimetype)) {
                   3842:             if ($$mimetype eq '') {
                   3843:                 my $mm = new File::MMagic;
                   3844:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3845:                 $$mimetype = $type;
                   3846:             }
                   3847:         }
                   3848:     }
1.1172.2.109  raeburn  3849:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3850:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3851:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3852:                                                        $allfiles,$codebase);
                   3853:             unless ($parse_result eq 'ok') {
                   3854:                 &logthis('Failed to parse '.$filepath.$file.
                   3855: 	   	         ' for embedded media: '.$parse_result); 
                   3856:             }
1.637     raeburn  3857:         }
1.1172.2.109  raeburn  3858:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3859:         my $format = $env{'form.scantron_format'};
                   3860:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3861:     }
1.860     raeburn  3862:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3863:         my $input = $filepath.'/'.$file;
                   3864:         my $output = $filepath.'/'.'tn-'.$file;
                   3865:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3866:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3867:         system({$args[0]} @args);
1.860     raeburn  3868:         if (-e $filepath.'/'.'tn-'.$file) {
                   3869:             $fetchthumb  = 1; 
                   3870:         }
                   3871:     }
1.858     raeburn  3872:  
1.259     www      3873: # Notify homeserver to grep it
                   3874: #
1.984     neumanie 3875:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3876:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3877:     if ($fetchresult eq 'ok') {
1.860     raeburn  3878:         if ($fetchthumb) {
                   3879:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3880:             if ($thumbresult ne 'ok') {
                   3881:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3882:                          $docuhome.': '.$thumbresult);
                   3883:             }
                   3884:         }
1.259     www      3885: #
1.258     www      3886: # Return the URL to it
1.494     albertel 3887:         return '/uploaded/'.$path.$file;
1.263     www      3888:     } else {
1.494     albertel 3889:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3890: 		 ': '.$fetchresult);
1.263     www      3891:         return '/adm/notfound.html';
1.858     raeburn  3892:     }
1.493     albertel 3893: }
                   3894: 
1.637     raeburn  3895: sub extract_embedded_items {
1.961     raeburn  3896:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3897:     my @state = ();
1.1164    raeburn  3898:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3899:     my %javafiles = (
                   3900:                       codebase => '',
                   3901:                       code => '',
                   3902:                       archive => ''
                   3903:                     );
                   3904:     my %mediafiles = (
                   3905:                       src => '',
                   3906:                       movie => '',
                   3907:                      );
1.648     raeburn  3908:     my $p;
                   3909:     if ($content) {
                   3910:         $p = HTML::LCParser->new($content);
                   3911:     } else {
1.961     raeburn  3912:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3913:     }
1.641     albertel 3914:     while (my $t=$p->get_token()) {
1.640     albertel 3915: 	if ($t->[0] eq 'S') {
                   3916: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3917: 	    push(@state, $tagname);
1.648     raeburn  3918:             if (lc($tagname) eq 'allow') {
                   3919:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3920:             }
1.640     albertel 3921: 	    if (lc($tagname) eq 'img') {
                   3922: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3923: 	    }
1.886     albertel 3924: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3925:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3926: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3927:                 }
1.886     albertel 3928: 	    }
1.645     raeburn  3929:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3930:                 my $src;
1.645     raeburn  3931:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3932:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3933:                 } else {
1.1164    raeburn  3934:                     if ($attr->{'src'} ne '') {
                   3935:                         $src = $attr->{'src'};
                   3936:                         &add_filetype($allfiles,$src,'src');
                   3937:                     }
                   3938:                 }
                   3939:                 my $text = $p->get_trimmed_text();
                   3940:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3941:                     my @swfargs = split(/,/,$1);
                   3942:                     foreach my $item (@swfargs) {
                   3943:                         $item =~ s/["']//g;
                   3944:                         $item =~ s/^\s+//;
                   3945:                         $item =~ s/\s+$//;
                   3946:                     }
                   3947:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3948:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3949:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3950:                         } else {
                   3951:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3952:                         }
                   3953:                     }
1.645     raeburn  3954:                 }
                   3955:             }
                   3956:             if (lc($tagname) eq 'link') {
                   3957:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3958:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3959:                 }
                   3960:             }
1.640     albertel 3961: 	    if (lc($tagname) eq 'object' ||
                   3962: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3963: 		foreach my $item (keys(%javafiles)) {
                   3964: 		    $javafiles{$item} = '';
                   3965: 		}
1.1164    raeburn  3966:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3967:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3968:                 }
1.640     albertel 3969: 	    }
                   3970: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3971: 		my $name = lc($attr->{'name'});
                   3972: 		foreach my $item (keys(%javafiles)) {
                   3973: 		    if ($name eq $item) {
                   3974: 			$javafiles{$item} = $attr->{'value'};
                   3975: 			last;
                   3976: 		    }
                   3977: 		}
1.1164    raeburn  3978:                 my $pathfrom;
1.640     albertel 3979: 		foreach my $item (keys(%mediafiles)) {
                   3980: 		    if ($name eq $item) {
1.1164    raeburn  3981:                         $pathfrom = $attr->{'value'};
                   3982:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3983: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3984: 			last;
                   3985: 		    }
                   3986: 		}
1.1164    raeburn  3987:                 if ($name eq 'flashvars') {
                   3988:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3989:                 }
                   3990:                 if ($pathfrom ne '') {
                   3991:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3992:                                          $pathfrom);
                   3993:                 }
1.640     albertel 3994: 	    }
                   3995: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3996: 		foreach my $item (keys(%javafiles)) {
                   3997: 		    if ($attr->{$item}) {
                   3998: 			$javafiles{$item} = $attr->{$item};
                   3999: 			last;
                   4000: 		    }
                   4001: 		}
                   4002: 		foreach my $item (keys(%mediafiles)) {
                   4003: 		    if ($attr->{$item}) {
                   4004: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4005: 			last;
                   4006: 		    }
                   4007: 		}
1.1164    raeburn  4008:                 if (lc($tagname) eq 'embed') {
                   4009:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4010:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4011:                                              $attr->{'src'});
                   4012:                     }
                   4013:                 }
1.640     albertel 4014: 	    }
1.1172.2.35  raeburn  4015:             if (lc($tagname) eq 'iframe') {
                   4016:                 my $src = $attr->{'src'} ;
                   4017:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4018:                     &add_filetype($allfiles,$src,'src');
                   4019:                 } elsif ($src =~ m{^/}) {
                   4020:                     if ($env{'request.course.id'}) {
                   4021:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4022:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4023:                         my $url = &hreflocation('',$fullpath);
                   4024:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4025:                             my $relpath = $1;
                   4026:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4027:                                 &add_filetype($allfiles,$1,'src');
                   4028:                             }
                   4029:                         }
                   4030:                     }
                   4031:                 }
                   4032:             }
1.1164    raeburn  4033:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4034:                 pop(@state);
1.1164    raeburn  4035:             }
1.640     albertel 4036: 	} elsif ($t->[0] eq 'E') {
                   4037: 	    my ($tagname) = ($t->[1]);
                   4038: 	    if ($javafiles{'codebase'} ne '') {
                   4039: 		$javafiles{'codebase'} .= '/';
                   4040: 	    }  
                   4041: 	    if (lc($tagname) eq 'applet' ||
                   4042: 		lc($tagname) eq 'object' ||
                   4043: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4044: 		) {
                   4045: 		foreach my $item (keys(%javafiles)) {
                   4046: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4047: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4048: 			&add_filetype($allfiles,$file,$item);
                   4049: 		    }
                   4050: 		}
                   4051: 	    } 
                   4052: 	    pop @state;
                   4053: 	}
                   4054:     }
1.1164    raeburn  4055:     foreach my $id (sort(keys(%flashvars))) {
                   4056:         if ($shockwave{$id} ne '') {
                   4057:             my @pairs = split(/\&/,$flashvars{$id});
                   4058:             foreach my $pair (@pairs) {
                   4059:                 my ($key,$value) = split(/\=/,$pair);
                   4060:                 if ($key eq 'thumb') {
                   4061:                     &add_filetype($allfiles,$value,$key);
                   4062:                 } elsif ($key eq 'content') {
                   4063:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4064:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4065:                     if ($ext ne '') {
                   4066:                         &add_filetype($allfiles,$path.$value,$ext);
                   4067:                     }
                   4068:                 }
                   4069:             }
                   4070:         }
                   4071:     }
1.637     raeburn  4072:     return 'ok';
                   4073: }
                   4074: 
1.639     albertel 4075: sub add_filetype {
                   4076:     my ($allfiles,$file,$type)=@_;
                   4077:     if (exists($allfiles->{$file})) {
                   4078: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4079: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4080: 	}
                   4081:     } else {
                   4082: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4083:     }
                   4084: }
                   4085: 
1.1164    raeburn  4086: sub embedded_dependency {
                   4087:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4088:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4089:         if (($identifier ne '') &&
                   4090:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4091:             ($pathfrom ne '')) {
                   4092:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4093:             foreach my $dep (@{$related->{$identifier}}) {
                   4094:                 &add_filetype($allfiles,$path.$dep,'object');
                   4095:             }
                   4096:         }
                   4097:     }
                   4098:     return;
                   4099: }
                   4100: 
1.1172.2.109  raeburn  4101: sub bubblesheet_converter {
                   4102:     my ($cdom,$fullpath,$config,$format) = @_;
                   4103:     if ((&domain($cdom) ne '') &&
                   4104:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4105:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4106:         my (%csvcols,%csvoptions);
                   4107:         if (ref($config->{'fields'}) eq 'HASH') {
                   4108:             %csvcols = %{$config->{'fields'}};
                   4109:         }
                   4110:         if (ref($config->{'options'}) eq 'HASH') {
                   4111:             %csvoptions = %{$config->{'options'}};
                   4112:         }
                   4113:         my %csvbynum = reverse(%csvcols);
                   4114:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4115:         if (keys(%scantronconf)) {
                   4116:             my %bynum = (
                   4117:                           $scantronconf{CODEstart} => 'CODEstart',
                   4118:                           $scantronconf{IDstart}   => 'IDstart',
                   4119:                           $scantronconf{PaperID}   => 'PaperID',
                   4120:                           $scantronconf{FirstName} => 'FirstName',
                   4121:                           $scantronconf{LastName}  => 'LastName',
                   4122:                           $scantronconf{Qstart}    => 'Qstart',
                   4123:                         );
                   4124:             my @ordered;
                   4125:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4126:                 push(@ordered,$bynum{$item});
                   4127:             }
                   4128:             my %mapstart = (
                   4129:                               CODEstart => 'CODE',
                   4130:                               IDstart   => 'ID',
                   4131:                               PaperID   => 'PaperID',
                   4132:                               FirstName => 'FirstName',
                   4133:                               LastName  => 'LastName',
                   4134:                               Qstart    => 'FirstQuestion',
                   4135:                            );
                   4136:             my %maplength = (
                   4137:                               CODEstart => 'CODElength',
                   4138:                               IDstart   => 'IDlength',
                   4139:                               PaperID   => 'PaperIDlength',
                   4140:                               FirstName => 'FirstNamelength',
                   4141:                               LastName  => 'LastNamelength',
                   4142:             );
                   4143:             if (open(my $fh,'<',$fullpath)) {
                   4144:                 my $output;
                   4145:                 my %lettdig = &letter_to_digits();
                   4146:                 my %diglett = reverse(%lettdig);
                   4147:                 my $numletts = scalar(keys(%lettdig));
                   4148:                 my $num = 0;
                   4149:                 while (my $line=<$fh>) {
                   4150:                     $num ++;
                   4151:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4152:                     $line =~ s{[\r\n]+$}{};
                   4153:                     my %found;
                   4154:                     my @values = split(/,/,$line);
                   4155:                     my ($qstart,$record);
                   4156:                     for (my $i=0; $i<@values; $i++) {
                   4157:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4158:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4159:                             if ($values[$i] eq '') {
                   4160:                                 $values[$i] = $scantronconf{'Qoff'};
                   4161:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4162:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4163:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4164:                                 }
                   4165:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4166:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4167:                                     $values[$i] = $diglett{$values[$i]};
                   4168:                                 }
                   4169:                             } else {
                   4170:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4171:                                     my $digit;
                   4172:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4173:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4174:                                         if ($values[$i] eq 'J') {
                   4175:                                             $digit += $numletts;
                   4176:                                         }
                   4177:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4178:                                         $digit = $values[$i]-1;
                   4179:                                         if ($values[$i] eq '0') {
                   4180:                                             $digit += $numletts;
                   4181:                                         }
                   4182:                                     }
                   4183:                                     my $qval='';
                   4184:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4185:                                         if ($j == $digit) {
                   4186:                                             $qval .= $scantronconf{'Qon'};
                   4187:                                         } else {
                   4188:                                             $qval .= $scantronconf{'Qoff'};
                   4189:                                         }
                   4190:                                     }
                   4191:                                     $values[$i] = $qval;
                   4192:                                 }
                   4193:                             }
                   4194:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4195:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4196:                             }
                   4197:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4198:                             if ($numblank > 0) {
                   4199:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4200:                             }
                   4201:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4202:                                 $qstart = $i;
                   4203:                                 $found{$csvbynum{$i}} = $values[$i];
                   4204:                             } else {
                   4205:                                 $found{'FirstQuestion'} .= $values[$i];
                   4206:                             }
                   4207:                         } elsif (exists($csvbynum{$i})) {
                   4208:                             if ($csvoptions{'rem'}) {
                   4209:                                 $values[$i] =~ s/^\s+//;
                   4210:                             }
                   4211:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4212:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4213:                                     $values[$i] = '0'.$values[$i];
                   4214:                                 }
                   4215:                             }
                   4216:                             $found{$csvbynum{$i}} = $values[$i];
                   4217:                         }
                   4218:                     }
                   4219:                     foreach my $item (@ordered) {
                   4220:                         my $currlength = 1+length($record);
                   4221:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4222:                         if ($numspaces > 0) {
                   4223:                             $record .= (' ' x $numspaces);
                   4224:                         }
                   4225:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4226:                             unless ($item eq 'Qstart') {
                   4227:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4228:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4229:                                 }
                   4230:                             }
                   4231:                             $record .= $found{$mapstart{$item}};
                   4232:                         }
                   4233:                     }
                   4234:                     $output .= "$record\n";
                   4235:                 }
                   4236:                 close($fh);
                   4237:                 if ($output) {
                   4238:                     if (open(my $fh,'>',$fullpath)) {
                   4239:                         print $fh $output;
                   4240:                         close($fh);
                   4241:                     }
                   4242:                 }
                   4243:             }
                   4244:         }
                   4245:         return;
                   4246:     }
                   4247: }
                   4248: 
                   4249: sub letter_to_digits {
                   4250:     my %lettdig = (
                   4251:                     A => 1,
                   4252:                     B => 2,
                   4253:                     C => 3,
                   4254:                     D => 4,
                   4255:                     E => 5,
                   4256:                     F => 6,
                   4257:                     G => 7,
                   4258:                     H => 8,
                   4259:                     I => 9,
                   4260:                     J => 0,
                   4261:                   );
                   4262:     return %lettdig;
                   4263: }
                   4264: 
                   4265: sub get_scantron_config {
                   4266:     my ($which,$cdom) = @_;
                   4267:     my @lines = &get_scantronformat_file($cdom);
                   4268:     my %config;
                   4269:     #FIXME probably should move to XML it has already gotten a bit much now
                   4270:     foreach my $line (@lines) {
                   4271:         my ($name,$descrip)=split(/:/,$line);
                   4272:         if ($name ne $which ) { next; }
                   4273:         chomp($line);
                   4274:         my @config=split(/:/,$line);
                   4275:         $config{'name'}=$config[0];
                   4276:         $config{'description'}=$config[1];
                   4277:         $config{'CODElocation'}=$config[2];
                   4278:         $config{'CODEstart'}=$config[3];
                   4279:         $config{'CODElength'}=$config[4];
                   4280:         $config{'IDstart'}=$config[5];
                   4281:         $config{'IDlength'}=$config[6];
                   4282:         $config{'Qstart'}=$config[7];
                   4283:         $config{'Qlength'}=$config[8];
                   4284:         $config{'Qoff'}=$config[9];
                   4285:         $config{'Qon'}=$config[10];
                   4286:         $config{'PaperID'}=$config[11];
                   4287:         $config{'PaperIDlength'}=$config[12];
                   4288:         $config{'FirstName'}=$config[13];
                   4289:         $config{'FirstNamelength'}=$config[14];
                   4290:         $config{'LastName'}=$config[15];
                   4291:         $config{'LastNamelength'}=$config[16];
                   4292:         $config{'BubblesPerRow'}=$config[17];
                   4293:         last;
                   4294:     }
                   4295:     return %config;
                   4296: }
                   4297: 
                   4298: sub get_scantronformat_file {
                   4299:     my ($cdom) = @_;
                   4300:     if ($cdom eq '') {
                   4301:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4302:     }
                   4303:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4304:     my $gottab = 0;
                   4305:     my @lines;
                   4306:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4307:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4308:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4309:             if ($formatfile ne '-1') {
                   4310:                 @lines = split("\n",$formatfile,-1);
                   4311:                 $gottab = 1;
                   4312:             }
                   4313:         }
                   4314:     }
                   4315:     if (!$gottab) {
                   4316:         my $confname = $cdom.'-domainconfig';
                   4317:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4318:         my $formatfile = &getfile($default);
                   4319:         if ($formatfile ne '-1') {
                   4320:             @lines = split("\n",$formatfile,-1);
                   4321:             $gottab = 1;
                   4322:         }
                   4323:     }
                   4324:     if (!$gottab) {
                   4325:         my @domains = &current_machine_domains();
                   4326:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4327:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4328:                 @lines = <$fh>;
                   4329:                 close($fh);
                   4330:             }
                   4331:         } else {
                   4332:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4333:                 @lines = <$fh>;
                   4334:                 close($fh);
                   4335:             }
                   4336:         }
                   4337:     }
                   4338:     return @lines;
                   4339: }
                   4340: 
1.493     albertel 4341: sub removeuploadedurl {
1.984     neumanie 4342:     my ($url)=@_;	
                   4343:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4344:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4345: }
                   4346: 
                   4347: sub removeuserfile {
                   4348:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4349:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4350:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4351:     if ($result eq 'ok') {	
1.798     raeburn  4352:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4353:             my $metafile = $fname.'.meta';
                   4354:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4355: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4356:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4357:             my $sqlresult = 
1.823     albertel 4358:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4359:                                         'portfolio_metadata',$group,
                   4360:                                         'delete');
1.798     raeburn  4361:         }
                   4362:     }
                   4363:     return $result;
1.257     www      4364: }
1.15      www      4365: 
1.530     albertel 4366: sub mkdiruserfile {
                   4367:     my ($docuname,$docudom,$dir)=@_;
                   4368:     my $home=&homeserver($docuname,$docudom);
                   4369:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4370: }
                   4371: 
1.531     albertel 4372: sub renameuserfile {
                   4373:     my ($docuname,$docudom,$old,$new)=@_;
                   4374:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4375:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4376:                         &escape("$old").':'.&escape("$new"),$home);
                   4377:     if ($result eq 'ok') {
                   4378:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4379:             my $oldmeta = $old.'.meta';
                   4380:             my $newmeta = $new.'.meta';
                   4381:             my $metaresult = 
                   4382:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4383: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4384:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4385:             my $sqlresult = 
1.823     albertel 4386:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4387:                                         'portfolio_metadata',$group,
                   4388:                                         'delete');
1.798     raeburn  4389:         }
                   4390:     }
                   4391:     return $result;
1.531     albertel 4392: }
                   4393: 
1.14      www      4394: # ------------------------------------------------------------------------- Log
                   4395: 
                   4396: sub log {
                   4397:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4398:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4399: }
                   4400: 
                   4401: # ------------------------------------------------------------------ Course Log
1.352     www      4402: #
                   4403: # This routine flushes several buffers of non-mission-critical nature
                   4404: #
1.157     www      4405: 
                   4406: sub flushcourselogs {
1.352     www      4407:     &logthis('Flushing log buffers');
                   4408: #
                   4409: # course logs
                   4410: # This is a log of all transactions in a course, which can be used
                   4411: # for data mining purposes
                   4412: #
                   4413: # It also collects the courseid database, which lists last transaction
                   4414: # times and course titles for all courseids
                   4415: #
                   4416:     my %courseidbuffer=();
1.921     raeburn  4417:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4418:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4419: 		          &escape($courselogs{$crsid}),
                   4420: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4421: 	    delete $courselogs{$crsid};
                   4422:         } else {
                   4423:             &logthis('Failed to flush log buffer for '.$crsid);
                   4424:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4425:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4426:                         " exceeded maximum size, deleting.</font>");
                   4427:                delete $courselogs{$crsid};
                   4428:             }
1.352     www      4429:         }
1.920     raeburn  4430:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4431:             'description' => $coursedescrbuf{$crsid},
                   4432:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4433:             'type'        => $coursetypebuf{$crsid},
                   4434:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4435:         };
1.191     harris41 4436:     }
1.352     www      4437: #
                   4438: # Write course id database (reverse lookup) to homeserver of courses 
                   4439: # Is used in pickcourse
                   4440: #
1.840     albertel 4441:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4442:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4443:                                     $courseidbuffer{$crs_home},
                   4444:                                     $crs_home,'timeonly');
1.352     www      4445:     }
                   4446: #
                   4447: # File accesses
                   4448: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4449: #
1.449     matthew  4450:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4451:         if ($entry =~ /___count$/) {
                   4452:             my ($dom,$name);
1.807     albertel 4453:             ($dom,$name,undef)=
1.811     albertel 4454: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4455:             if (! defined($dom) || $dom eq '' || 
                   4456:                 ! defined($name) || $name eq '') {
1.620     albertel 4457:                 my $cid = $env{'request.course.id'};
                   4458:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4459:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4460:             }
1.450     matthew  4461:             my $value = $accesshash{$entry};
                   4462:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4463:             my %temphash=($url => $value);
1.449     matthew  4464:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4465:             if ($result eq 'ok') {
                   4466:                 delete $accesshash{$entry};
                   4467:             }
                   4468:         } else {
1.811     albertel 4469:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4470:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4471:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4472:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4473:                 delete $accesshash{$entry};
                   4474:             }
1.185     www      4475:         }
1.191     harris41 4476:     }
1.352     www      4477: #
                   4478: # Roles
                   4479: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4480: #
1.800     albertel 4481:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4482:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4483: 	    split(/\:/,$entry);
                   4484:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4485:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4486:                 $rudom,$runame) eq 'ok') {
                   4487: 	    delete $userrolehash{$entry};
                   4488:         }
                   4489:     }
1.662     raeburn  4490: #
1.1172.2.90  raeburn  4491: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4492: #
                   4493:     my %domrolebuffer = ();
1.1000    raeburn  4494:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4495:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4496:         if ($domrolebuffer{$rudom}) {
                   4497:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4498:                       '='.&escape($domainrolehash{$entry});
                   4499:         } else {
                   4500:             $domrolebuffer{$rudom}.=&escape($entry).
                   4501:                       '='.&escape($domainrolehash{$entry});
                   4502:         }
                   4503:         delete $domainrolehash{$entry};
                   4504:     }
                   4505:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4506:         my %servers;
                   4507:         if (defined(&domain($dom,'primary'))) {
                   4508:             my $primary=&domain($dom,'primary');
                   4509:             my $hostname=&hostname($primary);
                   4510:             $servers{$primary} = $hostname;
                   4511:         } else {
                   4512:             %servers = &get_servers($dom,'library');
                   4513:         }
1.841     albertel 4514: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4515: 	    if (&reply('domroleput:'.$dom.':'.
                   4516: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4517: 	        last;
                   4518: 	    } else {
1.841     albertel 4519: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4520: 	    }
1.662     raeburn  4521:         }
                   4522:     }
1.186     www      4523:     $dumpcount++;
1.157     www      4524: }
                   4525: 
                   4526: sub courselog {
                   4527:     my $what=shift;
1.158     www      4528:     $what=time.':'.$what;
1.620     albertel 4529:     unless ($env{'request.course.id'}) { return ''; }
                   4530:     $coursedombuf{$env{'request.course.id'}}=
                   4531:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4532:     $coursenumbuf{$env{'request.course.id'}}=
                   4533:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4534:     $coursehombuf{$env{'request.course.id'}}=
                   4535:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4536:     $coursedescrbuf{$env{'request.course.id'}}=
                   4537:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4538:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4539:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4540:     $courseownerbuf{$env{'request.course.id'}}=
                   4541:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4542:     $coursetypebuf{$env{'request.course.id'}}=
                   4543:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4544:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4545: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4546:     } else {
1.620     albertel 4547: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4548:     }
1.620     albertel 4549:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4550: 	&flushcourselogs();
                   4551:     }
1.158     www      4552: }
                   4553: 
                   4554: sub courseacclog {
                   4555:     my $fnsymb=shift;
1.620     albertel 4556:     unless ($env{'request.course.id'}) { return ''; }
                   4557:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4558:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4559:         $what.=':POST';
1.583     matthew  4560:         # FIXME: Probably ought to escape things....
1.800     albertel 4561: 	foreach my $key (keys(%env)) {
                   4562:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4563:                 my $formitem = $1;
                   4564:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4565:                     $what.=':'.$formitem.'='.$env{$key};
                   4566:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4567:                     $what.=':'.$formitem.'='.$env{$key};
                   4568:                 }
1.158     www      4569:             }
1.191     harris41 4570:         }
1.583     matthew  4571:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4572:         # FIXME: We should not be depending on a form parameter that someone
                   4573:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4574:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4575:             $what.= ':POST';
                   4576:             # FIXME: Probably ought to escape things....
                   4577:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4578:                                  'crsdiscuss') {
1.620     albertel 4579:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4580:             }
                   4581:         }
1.158     www      4582:     }
                   4583:     &courselog($what);
1.149     www      4584: }
                   4585: 
1.185     www      4586: sub countacc {
                   4587:     my $url=&declutter(shift);
1.458     matthew  4588:     return if (! defined($url) || $url eq '');
1.620     albertel 4589:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4590: #
                   4591: # Mark that this url was used in this course
                   4592: #
1.620     albertel 4593:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4594: #
                   4595: # Increase the access count for this resource in this child process
                   4596: #
1.281     www      4597:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4598:     $accesshash{$key}++;
1.185     www      4599: }
1.349     www      4600: 
1.361     www      4601: sub linklog {
                   4602:     my ($from,$to)=@_;
                   4603:     $from=&declutter($from);
                   4604:     $to=&declutter($to);
                   4605:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4606:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4607: }
1.1160    www      4608: 
                   4609: sub statslog {
                   4610:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4611:     if ($users<2) { return; }
                   4612:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4613:             'course'       => $env{'request.course.id'},
                   4614:             'sections'     => '"all"',
                   4615:             'num_students' => $users,
                   4616:             'part'         => $part,
                   4617:             'symb'         => $symb,
                   4618:             'mean_tries'   => $av_attempts,
                   4619:             'deg_of_diff'  => $degdiff});
                   4620:     foreach my $key (keys(%dynstore)) {
                   4621:         $accesshash{$key}=$dynstore{$key};
                   4622:     }
                   4623: }
1.361     www      4624:   
1.349     www      4625: sub userrolelog {
                   4626:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4627:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4628:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4629:        $userrolehash
                   4630:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4631:                     =$tend.':'.$tstart;
1.662     raeburn  4632:     }
1.1169    droeschl 4633:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4634:        $userrolehash
                   4635:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4636:                     =$tend.':'.$tstart;
                   4637:     }
1.1172.2.90  raeburn  4638:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4639:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4640:        $domainrolehash
                   4641:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4642:                     = $tend.':'.$tstart;
                   4643:     }
1.351     www      4644: }
                   4645: 
1.957     raeburn  4646: sub courserolelog {
                   4647:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4648:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4649:         my $cdom = $1;
                   4650:         my $cnum = $2;
                   4651:         my $sec = $3;
                   4652:         my $namespace = 'rolelog';
                   4653:         my %storehash = (
                   4654:                            role    => $trole,
                   4655:                            start   => $tstart,
                   4656:                            end     => $tend,
                   4657:                            selfenroll => $selfenroll,
                   4658:                            context    => $context,
                   4659:                         );
                   4660:         if ($trole eq 'gr') {
                   4661:             $namespace = 'groupslog';
                   4662:             $storehash{'group'} = $sec;
                   4663:         } else {
                   4664:             $storehash{'section'} = $sec;
                   4665:         }
                   4666:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4667:                    $domain,$cnum,$cdom);
                   4668:         if (($trole ne 'st') || ($sec ne '')) {
                   4669:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4670:         }
                   4671:     }
                   4672:     return;
                   4673: }
                   4674: 
1.1172.2.9  raeburn  4675: sub domainrolelog {
                   4676:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4677:     if ($area =~ m{^/($match_domain)/$}) {
                   4678:         my $cdom = $1;
                   4679:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4680:         my $namespace = 'rolelog';
                   4681:         my %storehash = (
                   4682:                            role    => $trole,
                   4683:                            start   => $tstart,
                   4684:                            end     => $tend,
                   4685:                            context => $context,
                   4686:                         );
                   4687:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4688:                    $domain,$domconfiguser,$cdom);
                   4689:     }
                   4690:     return;
                   4691: 
                   4692: }
                   4693: 
                   4694: sub coauthorrolelog {
                   4695:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4696:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4697:         my $audom = $1;
                   4698:         my $auname = $2;
                   4699:         my $namespace = 'rolelog';
                   4700:         my %storehash = (
                   4701:                            role    => $trole,
                   4702:                            start   => $tstart,
                   4703:                            end     => $tend,
                   4704:                            context => $context,
                   4705:                         );
                   4706:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4707:                    $domain,$auname,$audom);
                   4708:     }
                   4709:     return;
                   4710: }
                   4711: 
1.351     www      4712: sub get_course_adv_roles {
1.948     raeburn  4713:     my ($cid,$codes) = @_;
1.620     albertel 4714:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4715:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4716:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4717:     my %nothide=();
1.800     albertel 4718:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4719:         if ($user !~ /:/) {
                   4720: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4721:         } else {
                   4722:             $nothide{$user}=1;
                   4723:         }
1.470     www      4724:     }
1.1172.2.23  raeburn  4725:     my @possdoms = ($coursehash{'domain'});
                   4726:     if ($coursehash{'checkforpriv'}) {
                   4727:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4728:     }
1.351     www      4729:     my %returnhash=();
                   4730:     my %dumphash=
                   4731:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4732:     my $now=time;
1.997     raeburn  4733:     my %privileged;
1.1000    raeburn  4734:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4735: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4736:         if (($tstart) && ($tstart<0)) { next; }
                   4737:         if (($tend) && ($tend<$now)) { next; }
                   4738:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4739:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4740: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4741:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4742:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4743: 	if ($role eq 'cr') { next; }
1.948     raeburn  4744:         if ($codes) {
                   4745:             if ($section) { $role .= ':'.$section; }
                   4746:             if ($returnhash{$role}) {
                   4747:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4748:             } else {
                   4749:                 $returnhash{$role}=$username.':'.$domain;
                   4750:             }
1.351     www      4751:         } else {
1.988     raeburn  4752:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4753:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4754:             if ($returnhash{$key}) {
                   4755: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4756:             } else {
                   4757:                 $returnhash{$key}=$username.':'.$domain;
                   4758:             }
1.351     www      4759:         }
1.948     raeburn  4760:     }
1.400     www      4761:     return %returnhash;
                   4762: }
                   4763: 
                   4764: sub get_my_roles {
1.937     raeburn  4765:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4766:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4767:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4768:     my (%dumphash,%nothide);
1.1086    raeburn  4769:     if ($context eq 'userroles') {
1.1166    raeburn  4770:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4771:     } else {
1.1172.2.23  raeburn  4772:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4773:         if ($hidepriv) {
                   4774:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4775:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4776:                 if ($user !~ /:/) {
                   4777:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4778:                 } else {
                   4779:                     $nothide{$user} = 1;
                   4780:                 }
                   4781:             }
                   4782:         }
1.858     raeburn  4783:     }
1.400     www      4784:     my %returnhash=();
                   4785:     my $now=time;
1.999     raeburn  4786:     my %privileged;
1.800     albertel 4787:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4788:         my ($role,$tend,$tstart);
                   4789:         if ($context eq 'userroles') {
1.1149    raeburn  4790:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4791: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4792:         } else {
                   4793:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4794:         }
1.400     www      4795:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4796:         my $status = 'active';
1.939     raeburn  4797:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4798:             $status = 'previous';
                   4799:         } 
                   4800:         if (($tstart) && ($now<$tstart)) {
                   4801:             $status = 'future';
                   4802:         }
                   4803:         if (ref($types) eq 'ARRAY') {
                   4804:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4805:                 next;
                   4806:             } 
                   4807:         } else {
                   4808:             if ($status ne 'active') {
                   4809:                 next;
                   4810:             }
                   4811:         }
1.867     raeburn  4812:         my ($rolecode,$username,$domain,$section,$area);
                   4813:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4814:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4815:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4816:         } else {
                   4817:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4818:         }
1.832     raeburn  4819:         if (ref($roledoms) eq 'ARRAY') {
                   4820:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4821:                 next;
                   4822:             }
                   4823:         }
                   4824:         if (ref($roles) eq 'ARRAY') {
                   4825:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4826:                 if ($role =~ /^cr\//) {
                   4827:                     if (!grep(/^cr$/,@{$roles})) {
                   4828:                         next;
                   4829:                     }
1.1104    raeburn  4830:                 } elsif ($role =~ /^gr\//) {
                   4831:                     if (!grep(/^gr$/,@{$roles})) {
                   4832:                         next;
                   4833:                     }
1.922     raeburn  4834:                 } else {
                   4835:                     next;
                   4836:                 }
1.832     raeburn  4837:             }
1.867     raeburn  4838:         }
1.937     raeburn  4839:         if ($hidepriv) {
1.1172.2.23  raeburn  4840:             my @privroles = ('dc','su');
1.999     raeburn  4841:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4842:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4843:             } else {
1.1172.2.23  raeburn  4844:                 my $possdoms = [$domain];
                   4845:                 if (ref($roledoms) eq 'ARRAY') {
                   4846:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4847:                 }
1.1172.2.23  raeburn  4848:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4849:                     if (!$nothide{$username.':'.$domain}) {
                   4850:                         next;
                   4851:                     }
                   4852:                 }
1.937     raeburn  4853:             }
                   4854:         }
1.933     raeburn  4855:         if ($withsec) {
                   4856:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4857:                 $tstart.':'.$tend;
                   4858:         } else {
                   4859:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4860:         }
1.832     raeburn  4861:     }
1.373     www      4862:     return %returnhash;
1.399     www      4863: }
                   4864: 
1.1172.2.89  raeburn  4865: sub get_all_adhocroles {
                   4866:     my ($dom) = @_;
                   4867:     my @roles_by_num = ();
                   4868:     my %domdefaults = &get_domain_defaults($dom);
                   4869:     my (%description,%access_in_dom,%access_info);
                   4870:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4871:         my $count = 0;
                   4872:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4873:         my %ordered;
                   4874:         foreach my $role (sort(keys(%domcurrent))) {
                   4875:             my ($order,$desc,$access_in_dom);
                   4876:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4877:                 $order = $domcurrent{$role}{'order'};
                   4878:                 $desc = $domcurrent{$role}{'desc'};
                   4879:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4880:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4881:             }
                   4882:             if ($order eq '') {
                   4883:                 $order = $count;
                   4884:             }
                   4885:             $ordered{$order} = $role;
                   4886:             if ($desc ne '') {
                   4887:                 $description{$role} = $desc;
                   4888:             } else {
                   4889:                 $description{$role}= $role;
                   4890:             }
                   4891:             $count++;
                   4892:         }
                   4893:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4894:             push(@roles_by_num,$ordered{$item});
                   4895:         }
                   4896:     }
                   4897:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4898: }
                   4899: 
                   4900: sub get_my_adhocroles {
                   4901:     my ($cid,$checkreg) = @_;
                   4902:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4903:     if ($env{'request.course.id'} eq $cid) {
                   4904:         $cdom = $env{'course.'.$cid.'.domain'};
                   4905:         $cnum = $env{'course.'.$cid.'.num'};
                   4906:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4907:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4908:         $cdom = $1;
                   4909:         $cnum = $2;
                   4910:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4911:                                      $cdom,$cnum);
                   4912:     }
                   4913:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4914:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4915:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4916:         if ($rosterhash{$user} ne '') {
                   4917:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4918:             return ([],{}) if ($type eq 'auto');
                   4919:         }
                   4920:     }
                   4921:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4922:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4923:             my $then=$env{'user.login.time'};
                   4924:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4925:             if (!$update) {
                   4926:                 $update = $then;
                   4927:             }
                   4928:             my @liveroles;
                   4929:             foreach my $role ('dh','da') {
                   4930:                 if ($env{"user.role.$role./$cdom/"}) {
                   4931:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4932:                     my $limit = $update;
                   4933:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4934:                         $limit = $then;
                   4935:                     }
                   4936:                     my $activerole = 1;
                   4937:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4938:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4939:                     if ($activerole) {
                   4940:                         push(@liveroles,$role);
                   4941:                     }
                   4942:                 }
                   4943:             }
                   4944:             if (@liveroles) {
1.1172.2.89  raeburn  4945:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4946:                     my ($accessref,$accessinfo,%access_in_dom);
                   4947:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4948:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4949:                         if (@{$roles_by_num}) {
                   4950:                             my %settings;
                   4951:                             if ($env{'request.course.id'} eq $cid) {
                   4952:                                 foreach my $envkey (keys(%env)) {
                   4953:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4954:                                         $settings{$1} = $env{$envkey};
                   4955:                                     }
                   4956:                                 }
                   4957:                             } else {
                   4958:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4959:                             }
                   4960:                             my %setincrs;
                   4961:                             if ($settings{'internal.adhocaccess'}) {
                   4962:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4963:                             }
                   4964:                             my @statuses;
                   4965:                             if ($env{'environment.inststatus'}) {
                   4966:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4967:                             }
                   4968:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4969:                             if (ref($accessref) eq 'HASH') {
                   4970:                                 %access_in_dom = %{$accessref};
                   4971:                             }
                   4972:                             foreach my $role (@{$roles_by_num}) {
                   4973:                                 my ($curraccess,@okstatus,@personnel);
                   4974:                                 if ($setincrs{$role}) {
                   4975:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4976:                                     if ($curraccess eq 'status') {
                   4977:                                         @okstatus = split(/\&/,$rest);
                   4978:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4979:                                         @personnel = split(/\&/,$rest);
                   4980:                                     }
                   4981:                                 } else {
                   4982:                                     $curraccess = $access_in_dom{$role};
                   4983:                                     if (ref($accessinfo) eq 'HASH') {
                   4984:                                         if ($curraccess eq 'status') {
                   4985:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4986:                                                 @okstatus = @{$accessinfo->{$role}};
                   4987:                                             }
                   4988:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4989:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4990:                                                 @personnel = @{$accessinfo->{$role}};
                   4991:                                             }
                   4992:                                         }
                   4993:                                     }
                   4994:                                 }
                   4995:                                 if ($curraccess eq 'none') {
                   4996:                                     next;
                   4997:                                 } elsif ($curraccess eq 'all') {
                   4998:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4999:                                 } elsif ($curraccess eq 'dh') {
                   5000:                                     if (grep(/^dh$/,@liveroles)) {
                   5001:                                         push(@possroles,$role);
                   5002:                                     } else {
                   5003:                                         next;
                   5004:                                     }
                   5005:                                 } elsif ($curraccess eq 'da') {
                   5006:                                     if (grep(/^da$/,@liveroles)) {
                   5007:                                         push(@possroles,$role);
                   5008:                                     } else {
                   5009:                                         next;
                   5010:                                     }
1.1172.2.89  raeburn  5011:                                 } elsif ($curraccess eq 'status') {
                   5012:                                     if (@okstatus) {
                   5013:                                         if (!@statuses) {
                   5014:                                             if (grep(/^default$/,@okstatus)) {
                   5015:                                                 push(@possroles,$role);
                   5016:                                             }
                   5017:                                         } else {
                   5018:                                             foreach my $status (@okstatus) {
                   5019:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5020:                                                     push(@possroles,$role);
                   5021:                                                     last;
                   5022:                                                 }
                   5023:                                             }
                   5024:                                         }
                   5025:                                     }
                   5026:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5027:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5028:                                         if ($curraccess eq 'exc') {
                   5029:                                             push(@possroles,$role);
                   5030:                                         }
                   5031:                                     } elsif ($curraccess eq 'inc') {
                   5032:                                         push(@possroles,$role);
                   5033:                                     }
                   5034:                                 }
                   5035:                             }
                   5036:                         }
                   5037:                     }
                   5038:                 }
                   5039:             }
                   5040:         }
                   5041:     }
                   5042:     unless (ref($description) eq 'HASH') {
                   5043:         if (ref($roles_by_num) eq 'ARRAY') {
                   5044:             my %desc;
                   5045:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5046:             $description = \%desc;
                   5047:         } else {
                   5048:             $description = {};
                   5049:         }
                   5050:     }
                   5051:     return (\@possroles,$description);
                   5052: }
                   5053: 
1.399     www      5054: # ----------------------------------------------------- Frontpage Announcements
                   5055: #
                   5056: #
                   5057: 
                   5058: sub postannounce {
                   5059:     my ($server,$text)=@_;
1.844     albertel 5060:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5061:     unless ($text=~/\w/) { $text=''; }
                   5062:     return &reply('setannounce:'.&escape($text),$server);
                   5063: }
                   5064: 
                   5065: sub getannounce {
1.448     albertel 5066: 
1.1172.2.96  raeburn  5067:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5068: 	my $announcement='';
1.800     albertel 5069: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5070: 	close($fh);
1.399     www      5071: 	if ($announcement=~/\w/) { 
                   5072: 	    return 
                   5073:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5074:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5075: 	} else {
                   5076: 	    return '';
                   5077: 	}
                   5078:     } else {
                   5079: 	return '';
                   5080:     }
1.351     www      5081: }
1.353     www      5082: 
                   5083: # ---------------------------------------------------------- Course ID routines
                   5084: # Deal with domain's nohist_courseid.db files
                   5085: #
                   5086: 
                   5087: sub courseidput {
1.921     raeburn  5088:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5089:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5090:     my $outcome;
                   5091:     if ($caller eq 'timeonly') {
                   5092:         my $cids = '';
                   5093:         foreach my $item (keys(%$storehash)) {
                   5094:             $cids.=&escape($item).'&';
                   5095:         }
                   5096:         $cids=~s/\&$//;
                   5097:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5098:                           $coursehome);       
                   5099:     } else {
                   5100:         my $items = '';
                   5101:         foreach my $item (keys(%$storehash)) {
                   5102:             $items.= &escape($item).'='.
                   5103:                      &freeze_escape($$storehash{$item}).'&';
                   5104:         }
                   5105:         $items=~s/\&$//;
                   5106:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5107:                           $coursehome);
1.918     raeburn  5108:     }
                   5109:     if ($outcome eq 'unknown_cmd') {
                   5110:         my $what;
                   5111:         foreach my $cid (keys(%$storehash)) {
                   5112:             $what .= &escape($cid).'=';
1.921     raeburn  5113:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5114:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5115:             }
                   5116:             $what =~ s/\:$/&/;
                   5117:         }
                   5118:         $what =~ s/\&$//;  
                   5119:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5120:     } else {
                   5121:         return $outcome;
                   5122:     }
1.353     www      5123: }
                   5124: 
                   5125: sub courseiddump {
1.921     raeburn  5126:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5127:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5128:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5129:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5130:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5131:     my $as_hash = 1;
                   5132:     my %returnhash;
                   5133:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5134:     my %libserv = &all_library();
                   5135:     foreach my $tryserver (keys(%libserv)) {
                   5136:         if ( (  $hostidflag == 1 
                   5137: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5138: 	     || (!defined($hostidflag)) ) {
                   5139: 
1.918     raeburn  5140: 	    if (($domfilter eq '') ||
                   5141: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5142:                 my $rep;
                   5143:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5144:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5145:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5146:                                 &escape($descfilter), &escape($instcodefilter),
                   5147:                                 &escape($ownerfilter), &escape($coursefilter),
                   5148:                                 &escape($typefilter), &escape($regexp_ok),
                   5149:                                 $as_hash, &escape($selfenrollonly),
                   5150:                                 &escape($catfilter), $showhidden, $caller,
                   5151:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5152:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5153:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5154:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5155:                 } else {
                   5156:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5157:                              $sincefilter.':'.&escape($descfilter).':'.
                   5158:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5159:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5160:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5161:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5162:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5163:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5164:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5165:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5166:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5167:                 }
                   5168: 
1.918     raeburn  5169:                 my @pairs=split(/\&/,$rep);
                   5170:                 foreach my $item (@pairs) {
                   5171:                     my ($key,$value)=split(/\=/,$item,2);
                   5172:                     $key = &unescape($key);
                   5173:                     next if ($key =~ /^error: 2 /);
                   5174:                     my $result = &thaw_unescape($value);
                   5175:                     if (ref($result) eq 'HASH') {
                   5176:                         $returnhash{$key}=$result;
                   5177:                     } else {
1.921     raeburn  5178:                         my @responses = split(/:/,$value);
                   5179:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5180:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5181:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5182:                         }
1.1008    raeburn  5183:                     }
1.353     www      5184:                 }
                   5185:             }
                   5186:         }
                   5187:     }
                   5188:     return %returnhash;
                   5189: }
                   5190: 
1.1055    raeburn  5191: sub courselastaccess {
                   5192:     my ($cdom,$cnum,$hostidref) = @_;
                   5193:     my %returnhash;
                   5194:     if ($cdom && $cnum) {
                   5195:         my $chome = &homeserver($cnum,$cdom);
                   5196:         if ($chome ne 'no_host') {
                   5197:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5198:             &extract_lastaccess(\%returnhash,$rep);
                   5199:         }
                   5200:     } else {
                   5201:         if (!$cdom) { $cdom=''; }
                   5202:         my %libserv = &all_library();
                   5203:         foreach my $tryserver (keys(%libserv)) {
                   5204:             if (ref($hostidref) eq 'ARRAY') {
                   5205:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5206:             } 
                   5207:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5208:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5209:                 &extract_lastaccess(\%returnhash,$rep);
                   5210:             }
                   5211:         }
                   5212:     }
                   5213:     return %returnhash;
                   5214: }
                   5215: 
                   5216: sub extract_lastaccess {
                   5217:     my ($returnhash,$rep) = @_;
                   5218:     if (ref($returnhash) eq 'HASH') {
                   5219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5221:                  $rep eq '') {
                   5222:             my @pairs=split(/\&/,$rep);
                   5223:             foreach my $item (@pairs) {
                   5224:                 my ($key,$value)=split(/\=/,$item,2);
                   5225:                 $key = &unescape($key);
                   5226:                 next if ($key =~ /^error: 2 /);
                   5227:                 $returnhash->{$key} = &thaw_unescape($value);
                   5228:             }
                   5229:         }
                   5230:     }
                   5231:     return;
                   5232: }
                   5233: 
1.658     raeburn  5234: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5235: 
                   5236: sub dcmailput {
1.685     raeburn  5237:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5238:     my $status = &Apache::lonnet::critical(
1.740     www      5239:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5240:        &escape($message),$server);
1.662     raeburn  5241:     return $status;
                   5242: }
                   5243: 
1.658     raeburn  5244: sub dcmaildump {
                   5245:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5246:     my %returnhash=();
1.846     albertel 5247: 
                   5248:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5249:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5250:                                                          &escape($enddate).':';
                   5251: 	my @esc_senders=map { &escape($_)} @$senders;
                   5252: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5253: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5254:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5255:             if (($key) && ($value)) {
                   5256:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5257:             }
                   5258:         }
                   5259:     }
                   5260:     return %returnhash;
                   5261: }
1.662     raeburn  5262: # ---------------------------------------------------------- Domain roles
                   5263: 
                   5264: sub get_domain_roles {
                   5265:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5266:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5267:         $startdate = '.';
                   5268:     }
1.1018    raeburn  5269:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5270:         $enddate = '.';
                   5271:     }
1.922     raeburn  5272:     my $rolelist;
                   5273:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5274:         $rolelist = join('&',@{$roles});
1.922     raeburn  5275:     }
1.662     raeburn  5276:     my %personnel = ();
1.841     albertel 5277: 
                   5278:     my %servers = &get_servers($dom,'library');
                   5279:     foreach my $tryserver (keys(%servers)) {
                   5280: 	%{$personnel{$tryserver}}=();
                   5281: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5282: 					    &escape($startdate).':'.
                   5283: 					    &escape($enddate).':'.
                   5284: 					    &escape($rolelist), $tryserver))) {
                   5285: 	    my ($key,$value) = split(/\=/,$line,2);
                   5286: 	    if (($key) && ($value)) {
                   5287: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5288: 	    }
                   5289: 	}
1.662     raeburn  5290:     }
                   5291:     return %personnel;
                   5292: }
1.658     raeburn  5293: 
1.1172.2.89  raeburn  5294: sub get_active_domroles {
                   5295:     my ($dom,$roles) = @_;
                   5296:     return () unless (ref($roles) eq 'ARRAY');
                   5297:     my $now = time;
                   5298:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5299:     my %domroles;
                   5300:     foreach my $server (keys(%dompersonnel)) {
                   5301:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5302:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5303:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5304:         }
                   5305:     }
                   5306:     return %domroles;
                   5307: }
                   5308: 
1.1057    www      5309: # ----------------------------------------------------------- Interval timing 
1.149     www      5310: 
1.1153    www      5311: {
                   5312: # Caches needed for speedup of navmaps
                   5313: # We don't want to cache this for very long at all (5 seconds at most)
                   5314: # 
                   5315: # The user for whom we cache
                   5316: my $cachedkey='';
                   5317: # The cached times for this user
                   5318: my %cachedtimes=();
                   5319: # When this was last done
1.1172.2.66  raeburn  5320: my $cachedtime='';
1.1153    www      5321: 
                   5322: sub load_all_first_access {
1.1154    raeburn  5323:     my ($uname,$udom)=@_;
1.1156    www      5324:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5325:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5326:         return;
                   5327:     }
                   5328:     $cachedtime=time;
                   5329:     $cachedkey=$uname.':'.$udom;
                   5330:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5331: }
                   5332: 
1.504     albertel 5333: sub get_first_access {
1.1162    raeburn  5334:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5335:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5336:     if ($argsymb) { $symb=$argsymb; }
                   5337:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5338:     if ($argmap) { $map = $argmap; }
1.926     albertel 5339:     if ($type eq 'course') {
                   5340: 	$res='course';
                   5341:     } elsif ($type eq 'map') {
1.588     albertel 5342: 	$res=&symbread($map);
                   5343:     } else {
                   5344: 	$res=$symb;
                   5345:     }
1.1153    www      5346:     &load_all_first_access($uname,$udom);
                   5347:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5348: }
                   5349: 
                   5350: sub set_first_access {
1.1162    raeburn  5351:     my ($type,$interval)=@_;
1.790     albertel 5352:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5353:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5354:     if ($type eq 'course') {
                   5355: 	$res='course';
                   5356:     } elsif ($type eq 'map') {
1.588     albertel 5357: 	$res=&symbread($map);
                   5358:     } else {
                   5359: 	$res=$symb;
                   5360:     }
1.1153    www      5361:     $cachedkey='';
1.1162    raeburn  5362:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5363:     if ($firstaccess) {
                   5364:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5365:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5366:                  "in $courseid");
                   5367:         return 'already_set';
                   5368:     } else {
1.1162    raeburn  5369:         my $start = time;
                   5370: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5371:                           $udom,$uname);
                   5372:         if ($putres eq 'ok') {
                   5373:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5374:                  $udom,$uname); 
                   5375:             &appenv(
                   5376:                      {
                   5377:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5378:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5379:                      }
                   5380:                   );
1.1172.2.97  raeburn  5381:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5382:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5383:             }
1.1172.2.102  raeburn  5384:         } elsif ($putres ne 'refused') {
                   5385:             &logthis("Result: $putres when attempting to set first access time ".
                   5386:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5387:         }
                   5388:         return $putres;
1.505     albertel 5389:     }
                   5390:     return 'already_set';
1.504     albertel 5391: }
1.1153    www      5392: }
1.1172.2.32  raeburn  5393: 
                   5394: sub checkout {
                   5395:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5396:     my $now=time;
                   5397:     my $lonhost=$perlvar{'lonHostID'};
                   5398:     my $infostr=&escape(
                   5399:                  'CHECKOUTTOKEN&'.
                   5400:                  $tuname.'&'.
                   5401:                  $tudom.'&'.
                   5402:                  $tcrsid.'&'.
                   5403:                  $symb.'&'.
                   5404:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5405:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5406:     if ($token=~/^error\:/) {
                   5407:         &logthis("<font color=\"blue\">WARNING: ".
                   5408:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5409:                  "</font>");
                   5410:         return '';
                   5411:     }
                   5412: 
                   5413:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5414:     $token=~tr/a-z/A-Z/;
                   5415: 
                   5416:     my %infohash=('resource.0.outtoken' => $token,
                   5417:                   'resource.0.checkouttime' => $now,
                   5418:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5419: 
                   5420:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5421:        return '';
                   5422:     } else {
                   5423:         &logthis("<font color=\"blue\">WARNING: ".
                   5424:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5425:                  "</font>");
                   5426:     }
                   5427: 
                   5428:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5429:                          &escape('Checkout '.$infostr.' - '.
                   5430:                                                  $token)) ne 'ok') {
                   5431:         return '';
                   5432:     } else {
                   5433:         &logthis("<font color=\"blue\">WARNING: ".
                   5434:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5435:                  "</font>");
                   5436:     }
                   5437:     return $token;
                   5438: }
                   5439: 
                   5440: # ------------------------------------------------------------ Check in an item
                   5441: 
                   5442: sub checkin {
                   5443:     my $token=shift;
                   5444:     my $now=time;
                   5445:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5446:     $lonhost=~tr/A-Z/a-z/;
                   5447:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5448:     $dtoken=~s/\W/\_/g;
                   5449:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5450:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5451: 
                   5452:     unless (($tuname) && ($tudom)) {
                   5453:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5454:         return '';
                   5455:     }
                   5456: 
                   5457:     unless (&allowed('mgr',$tcrsid)) {
                   5458:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5459:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5460:         return '';
                   5461:     }
                   5462: 
                   5463:     my %infohash=('resource.0.intoken' => $token,
                   5464:                   'resource.0.checkintime' => $now,
                   5465:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5466: 
                   5467:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5468:        return '';
                   5469:     }
                   5470: 
                   5471:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5472:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5473:         return '';
                   5474:     }
                   5475: 
                   5476:     return ($symb,$tuname,$tudom,$tcrsid);
                   5477: }
                   5478: 
1.110     www      5479: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5480: 
                   5481: sub expirespread {
                   5482:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5483:     my $cid=$env{'request.course.id'}; 
1.110     www      5484:     if ($cid) {
                   5485:        my $now=time;
                   5486:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5487:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5488:                             $env{'course.'.$cid.'.num'}.
1.110     www      5489: 	        	    ':nohist_expirationdates:'.
                   5490:                             &escape($key).'='.$now,
1.620     albertel 5491:                             $env{'course.'.$cid.'.home'})
1.110     www      5492:     }
                   5493:     return 'ok';
1.14      www      5494: }
                   5495: 
1.109     www      5496: # ----------------------------------------------------- Devalidate Spreadsheets
                   5497: 
                   5498: sub devalidate {
1.325     www      5499:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5500:     my $cid=$env{'request.course.id'}; 
1.109     www      5501:     if ($cid) {
1.391     matthew  5502:         # delete the stored spreadsheets for
                   5503:         # - the student level sheet of this user in course's homespace
                   5504:         # - the assessment level sheet for this resource 
                   5505:         #   for this user in user's homespace
1.553     albertel 5506: 	# - current conditional state info
1.325     www      5507: 	my $key=$uname.':'.$udom.':';
1.109     www      5508:         my $status=
1.299     matthew  5509: 	    &del('nohist_calculatedsheets',
1.391     matthew  5510: 		 [$key.'studentcalc:'],
1.620     albertel 5511: 		 $env{'course.'.$cid.'.domain'},
                   5512: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5513: 		.' '.
                   5514: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5515: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5516:         unless ($status eq 'ok ok') {
                   5517:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5518:                     $uname.' at '.$udom.' for '.
1.109     www      5519: 		    $symb.': '.$status);
1.133     albertel 5520:         }
1.553     albertel 5521: 	&delenv('user.state.'.$cid);
1.109     www      5522:     }
                   5523: }
                   5524: 
1.265     albertel 5525: sub get_scalar {
                   5526:     my ($string,$end) = @_;
                   5527:     my $value;
                   5528:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5529: 	$value = $1;
                   5530:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5531: 	$value = $1;
                   5532:     }
                   5533:     return &unescape($value);
                   5534: }
                   5535: 
                   5536: sub array2str {
                   5537:   my (@array) = @_;
                   5538:   my $result=&arrayref2str(\@array);
                   5539:   $result=~s/^__ARRAY_REF__//;
                   5540:   $result=~s/__END_ARRAY_REF__$//;
                   5541:   return $result;
                   5542: }
                   5543: 
1.204     albertel 5544: sub arrayref2str {
                   5545:   my ($arrayref) = @_;
1.265     albertel 5546:   my $result='__ARRAY_REF__';
1.204     albertel 5547:   foreach my $elem (@$arrayref) {
1.265     albertel 5548:     if(ref($elem) eq 'ARRAY') {
                   5549:       $result.=&arrayref2str($elem).'&';
                   5550:     } elsif(ref($elem) eq 'HASH') {
                   5551:       $result.=&hashref2str($elem).'&';
                   5552:     } elsif(ref($elem)) {
                   5553:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5554:     } else {
                   5555:       $result.=&escape($elem).'&';
                   5556:     }
                   5557:   }
                   5558:   $result=~s/\&$//;
1.265     albertel 5559:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5560:   return $result;
                   5561: }
                   5562: 
1.168     albertel 5563: sub hash2str {
1.204     albertel 5564:   my (%hash) = @_;
                   5565:   my $result=&hashref2str(\%hash);
1.265     albertel 5566:   $result=~s/^__HASH_REF__//;
                   5567:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5568:   return $result;
                   5569: }
                   5570: 
                   5571: sub hashref2str {
                   5572:   my ($hashref)=@_;
1.265     albertel 5573:   my $result='__HASH_REF__';
1.800     albertel 5574:   foreach my $key (sort(keys(%$hashref))) {
                   5575:     if (ref($key) eq 'ARRAY') {
                   5576:       $result.=&arrayref2str($key).'=';
                   5577:     } elsif (ref($key) eq 'HASH') {
                   5578:       $result.=&hashref2str($key).'=';
                   5579:     } elsif (ref($key)) {
1.265     albertel 5580:       $result.='=';
1.800     albertel 5581:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5582:     } else {
1.1132    raeburn  5583: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5584:     }
                   5585: 
1.800     albertel 5586:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5587:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5588:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5589:       $result.=&hashref2str($hashref->{$key}).'&';
                   5590:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5591:        $result.='&';
1.800     albertel 5592:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5593:     } else {
1.800     albertel 5594:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5595:     }
                   5596:   }
1.168     albertel 5597:   $result=~s/\&$//;
1.265     albertel 5598:   $result .= '__END_HASH_REF__';
1.168     albertel 5599:   return $result;
                   5600: }
                   5601: 
                   5602: sub str2hash {
1.265     albertel 5603:     my ($string)=@_;
                   5604:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5605:     return %$hash;
                   5606: }
                   5607: 
                   5608: sub str2hashref {
1.168     albertel 5609:   my ($string) = @_;
1.265     albertel 5610: 
                   5611:   my %hash;
                   5612: 
                   5613:   if($string !~ /^__HASH_REF__/) {
                   5614:       if (! ($string eq '' || !defined($string))) {
                   5615: 	  $hash{'error'}='Not hash reference';
                   5616:       }
                   5617:       return (\%hash, $string);
                   5618:   }
                   5619: 
                   5620:   $string =~ s/^__HASH_REF__//;
                   5621: 
                   5622:   while($string !~ /^__END_HASH_REF__/) {
                   5623:       #key
                   5624:       my $key='';
                   5625:       if($string =~ /^__HASH_REF__/) {
                   5626:           ($key, $string)=&str2hashref($string);
                   5627:           if(defined($key->{'error'})) {
                   5628:               $hash{'error'}='Bad data';
                   5629:               return (\%hash, $string);
                   5630:           }
                   5631:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5632:           ($key, $string)=&str2arrayref($string);
                   5633:           if($key->[0] eq 'Array reference error') {
                   5634:               $hash{'error'}='Bad data';
                   5635:               return (\%hash, $string);
                   5636:           }
                   5637:       } else {
                   5638:           $string =~ s/^(.*?)=//;
1.267     albertel 5639: 	  $key=&unescape($1);
1.265     albertel 5640:       }
                   5641:       $string =~ s/^=//;
                   5642: 
                   5643:       #value
                   5644:       my $value='';
                   5645:       if($string =~ /^__HASH_REF__/) {
                   5646:           ($value, $string)=&str2hashref($string);
                   5647:           if(defined($value->{'error'})) {
                   5648:               $hash{'error'}='Bad data';
                   5649:               return (\%hash, $string);
                   5650:           }
                   5651:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5652:           ($value, $string)=&str2arrayref($string);
                   5653:           if($value->[0] eq 'Array reference error') {
                   5654:               $hash{'error'}='Bad data';
                   5655:               return (\%hash, $string);
                   5656:           }
                   5657:       } else {
                   5658: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5659:       }
                   5660:       $string =~ s/^&//;
                   5661: 
                   5662:       $hash{$key}=$value;
1.204     albertel 5663:   }
1.265     albertel 5664: 
                   5665:   $string =~ s/^__END_HASH_REF__//;
                   5666: 
                   5667:   return (\%hash, $string);
1.204     albertel 5668: }
                   5669: 
                   5670: sub str2array {
1.265     albertel 5671:     my ($string)=@_;
                   5672:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5673:     return @$array;
                   5674: }
                   5675: 
                   5676: sub str2arrayref {
1.204     albertel 5677:   my ($string) = @_;
1.265     albertel 5678:   my @array;
                   5679: 
                   5680:   if($string !~ /^__ARRAY_REF__/) {
                   5681:       if (! ($string eq '' || !defined($string))) {
                   5682: 	  $array[0]='Array reference error';
                   5683:       }
                   5684:       return (\@array, $string);
                   5685:   }
                   5686: 
                   5687:   $string =~ s/^__ARRAY_REF__//;
                   5688: 
                   5689:   while($string !~ /^__END_ARRAY_REF__/) {
                   5690:       my $value='';
                   5691:       if($string =~ /^__HASH_REF__/) {
                   5692:           ($value, $string)=&str2hashref($string);
                   5693:           if(defined($value->{'error'})) {
                   5694:               $array[0] ='Array reference error';
                   5695:               return (\@array, $string);
                   5696:           }
                   5697:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5698:           ($value, $string)=&str2arrayref($string);
                   5699:           if($value->[0] eq 'Array reference error') {
                   5700:               $array[0] ='Array reference error';
                   5701:               return (\@array, $string);
                   5702:           }
                   5703:       } else {
                   5704: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5705:       }
                   5706:       $string =~ s/^&//;
                   5707: 
                   5708:       push(@array, $value);
1.191     harris41 5709:   }
1.265     albertel 5710: 
                   5711:   $string =~ s/^__END_ARRAY_REF__//;
                   5712: 
                   5713:   return (\@array, $string);
1.168     albertel 5714: }
                   5715: 
1.167     albertel 5716: # -------------------------------------------------------------------Temp Store
                   5717: 
1.168     albertel 5718: sub tmpreset {
                   5719:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5720:   if (!$symb) {
                   5721:     $symb=&symbread();
1.620     albertel 5722:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5723:   }
                   5724:   $symb=escape($symb);
                   5725: 
1.620     albertel 5726:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5727:   $namespace=~s/\//\_/g;
                   5728:   $namespace=~s/\W//g;
                   5729: 
1.620     albertel 5730:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5731:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5732:   if ($domain eq 'public' && $stuname eq 'public') {
                   5733:       $stuname=$ENV{'REMOTE_ADDR'};
                   5734:   }
1.1117    foxr     5735:   my $path=LONCAPA::tempdir();
1.168     albertel 5736:   my %hash;
                   5737:   if (tie(%hash,'GDBM_File',
                   5738: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5739: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5740:     foreach my $key (keys(%hash)) {
1.180     albertel 5741:       if ($key=~ /:$symb/) {
1.168     albertel 5742: 	delete($hash{$key});
                   5743:       }
                   5744:     }
                   5745:   }
                   5746: }
                   5747: 
1.167     albertel 5748: sub tmpstore {
1.168     albertel 5749:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5750: 
                   5751:   if (!$symb) {
                   5752:     $symb=&symbread();
1.620     albertel 5753:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5754:   }
                   5755:   $symb=escape($symb);
                   5756: 
                   5757:   if (!$namespace) {
                   5758:     # I don't think we would ever want to store this for a course.
                   5759:     # it seems this will only be used if we don't have a course.
1.620     albertel 5760:     #$namespace=$env{'request.course.id'};
1.168     albertel 5761:     #if (!$namespace) {
1.620     albertel 5762:       $namespace=$env{'request.state'};
1.168     albertel 5763:     #}
                   5764:   }
                   5765:   $namespace=~s/\//\_/g;
                   5766:   $namespace=~s/\W//g;
1.620     albertel 5767:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5768:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5769:   if ($domain eq 'public' && $stuname eq 'public') {
                   5770:       $stuname=$ENV{'REMOTE_ADDR'};
                   5771:   }
1.168     albertel 5772:   my $now=time;
                   5773:   my %hash;
1.1117    foxr     5774:   my $path=LONCAPA::tempdir();
1.168     albertel 5775:   if (tie(%hash,'GDBM_File',
                   5776: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5777: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5778:     $hash{"version:$symb"}++;
                   5779:     my $version=$hash{"version:$symb"};
                   5780:     my $allkeys=''; 
                   5781:     foreach my $key (keys(%$storehash)) {
                   5782:       $allkeys.=$key.':';
1.591     albertel 5783:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5784:     }
                   5785:     $hash{"$version:$symb:timestamp"}=$now;
                   5786:     $allkeys.='timestamp';
                   5787:     $hash{"$version:keys:$symb"}=$allkeys;
                   5788:     if (untie(%hash)) {
                   5789:       return 'ok';
                   5790:     } else {
                   5791:       return "error:$!";
                   5792:     }
                   5793:   } else {
                   5794:     return "error:$!";
                   5795:   }
                   5796: }
1.167     albertel 5797: 
1.168     albertel 5798: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5799: 
1.168     albertel 5800: sub tmprestore {
                   5801:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5802: 
1.168     albertel 5803:   if (!$symb) {
                   5804:     $symb=&symbread();
1.620     albertel 5805:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5806:   }
                   5807:   $symb=escape($symb);
                   5808: 
1.620     albertel 5809:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5810: 
1.620     albertel 5811:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5812:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5813:   if ($domain eq 'public' && $stuname eq 'public') {
                   5814:       $stuname=$ENV{'REMOTE_ADDR'};
                   5815:   }
1.168     albertel 5816:   my %returnhash;
                   5817:   $namespace=~s/\//\_/g;
                   5818:   $namespace=~s/\W//g;
                   5819:   my %hash;
1.1117    foxr     5820:   my $path=LONCAPA::tempdir();
1.168     albertel 5821:   if (tie(%hash,'GDBM_File',
                   5822: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5823: 	  &GDBM_READER(),0640)) {
1.168     albertel 5824:     my $version=$hash{"version:$symb"};
                   5825:     $returnhash{'version'}=$version;
                   5826:     my $scope;
                   5827:     for ($scope=1;$scope<=$version;$scope++) {
                   5828:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5829:       my @keys=split(/:/,$vkeys);
                   5830:       my $key;
                   5831:       $returnhash{"$scope:keys"}=$vkeys;
                   5832:       foreach $key (@keys) {
1.591     albertel 5833: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5834: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5835:       }
                   5836:     }
1.168     albertel 5837:     if (!(untie(%hash))) {
                   5838:       return "error:$!";
                   5839:     }
                   5840:   } else {
                   5841:     return "error:$!";
                   5842:   }
                   5843:   return %returnhash;
1.167     albertel 5844: }
                   5845: 
1.9       www      5846: # ----------------------------------------------------------------------- Store
                   5847: 
                   5848: sub store {
1.1172.2.64  raeburn  5849:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5850:     my $home='';
                   5851: 
1.168     albertel 5852:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5853: 
1.213     www      5854:     $symb=&symbclean($symb);
1.122     albertel 5855:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5856: 
1.620     albertel 5857:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5858:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5859: 
                   5860:     &devalidate($symb,$stuname,$domain);
1.109     www      5861: 
                   5862:     $symb=escape($symb);
1.187     www      5863:     if (!$namespace) { 
1.620     albertel 5864:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5865:           return ''; 
                   5866:        } 
                   5867:     }
1.620     albertel 5868:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5869: 
                   5870:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5871:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5872: 
1.12      www      5873:     my $namevalue='';
1.800     albertel 5874:     foreach my $key (keys(%$storehash)) {
                   5875:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5876:     }
1.12      www      5877:     $namevalue=~s/\&$//;
1.187     www      5878:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5879:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5880: }
                   5881: 
1.47      www      5882: # -------------------------------------------------------------- Critical Store
                   5883: 
                   5884: sub cstore {
1.1172.2.64  raeburn  5885:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5886:     my $home='';
                   5887: 
1.168     albertel 5888:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5889: 
1.213     www      5890:     $symb=&symbclean($symb);
1.122     albertel 5891:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5892: 
1.620     albertel 5893:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5894:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5895: 
                   5896:     &devalidate($symb,$stuname,$domain);
1.109     www      5897: 
                   5898:     $symb=escape($symb);
1.187     www      5899:     if (!$namespace) { 
1.620     albertel 5900:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5901:           return ''; 
                   5902:        } 
                   5903:     }
1.620     albertel 5904:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5905: 
                   5906:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5907:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5908: 
1.47      www      5909:     my $namevalue='';
1.800     albertel 5910:     foreach my $key (keys(%$storehash)) {
                   5911:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5912:     }
1.47      www      5913:     $namevalue=~s/\&$//;
1.187     www      5914:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5915:     return critical
1.1172.2.64  raeburn  5916:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5917: }
                   5918: 
1.9       www      5919: # --------------------------------------------------------------------- Restore
                   5920: 
                   5921: sub restore {
1.124     www      5922:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5923:     my $home='';
                   5924: 
1.168     albertel 5925:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5926: 
1.122     albertel 5927:     if (!$symb) {
1.1172.2.26  raeburn  5928:         return if ($namespace eq 'courserequests');
                   5929:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5930:     } else {
1.1172.2.26  raeburn  5931:         unless ($namespace eq 'courserequests') {
                   5932:             $symb=&escape(&symbclean($symb));
                   5933:         }
1.122     albertel 5934:     }
1.188     www      5935:     if (!$namespace) { 
1.620     albertel 5936:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5937:           return ''; 
                   5938:        } 
                   5939:     }
1.620     albertel 5940:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5941:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5942:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5943:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5944: 
1.12      www      5945:     my %returnhash=();
1.800     albertel 5946:     foreach my $line (split(/\&/,$answer)) {
                   5947: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5948:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5949:     }
1.75      www      5950:     my $version;
                   5951:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5952:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5953:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5954:        }
1.75      www      5955:     }
1.13      www      5956:     return %returnhash;
1.34      www      5957: }
                   5958: 
                   5959: # ---------------------------------------------------------- Course Description
1.1118    foxr     5960: #
                   5961: #  
1.34      www      5962: 
                   5963: sub coursedescription {
1.731     albertel 5964:     my ($courseid,$args)=@_;
1.34      www      5965:     $courseid=~s/^\///;
1.49      www      5966:     $courseid=~s/\_/\//g;
1.34      www      5967:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5968:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5969:     my $normalid=$cdomain.'_'.$cnum;
                   5970:     # need to always cache even if we get errors otherwise we keep 
                   5971:     # trying and trying and trying to get the course description.
                   5972:     my %envhash=();
                   5973:     my %returnhash=();
1.731     albertel 5974:     
                   5975:     my $expiretime=600;
                   5976:     if ($env{'request.course.id'} eq $normalid) {
                   5977: 	$expiretime=120;
                   5978:     }
                   5979: 
                   5980:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5981:     if (!$args->{'freshen_cache'}
                   5982: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5983: 	foreach my $key (keys(%env)) {
                   5984: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5985: 	    my ($setting) = $1;
                   5986: 	    $returnhash{$setting} = $env{$key};
                   5987: 	}
                   5988: 	return %returnhash;
                   5989:     }
                   5990: 
1.1118    foxr     5991:     # get the data again
                   5992: 
1.731     albertel 5993:     if (!$args->{'one_time'}) {
                   5994: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5995:     }
1.811     albertel 5996: 
1.34      www      5997:     if ($chome ne 'no_host') {
1.302     albertel 5998:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5999:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6000: 	   my $username = $env{'user.name'}; # Defult username
                   6001: 	   if(defined $args->{'user'}) {
                   6002: 	       $username = $args->{'user'};
                   6003: 	   }
1.129     albertel 6004:            $returnhash{'home'}= $chome;
                   6005: 	   $returnhash{'domain'} = $cdomain;
                   6006: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6007:            if (!defined($returnhash{'type'})) {
                   6008:                $returnhash{'type'} = 'Course';
                   6009:            }
1.130     albertel 6010:            while (my ($name,$value) = each %returnhash) {
1.53      www      6011:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6012:            }
1.270     www      6013:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6014:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6015: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6016:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6017:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6018:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6019:        }
                   6020:     }
1.731     albertel 6021:     if (!$args->{'one_time'}) {
1.949     raeburn  6022: 	&appenv(\%envhash);
1.731     albertel 6023:     }
1.302     albertel 6024:     return %returnhash;
1.461     www      6025: }
                   6026: 
1.1080    raeburn  6027: sub update_released_required {
                   6028:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6029:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6030:         $cid = $env{'request.course.id'};
                   6031:         $cdom = $env{'course.'.$cid.'.domain'};
                   6032:         $cnum = $env{'course.'.$cid.'.num'};
                   6033:         $chome = $env{'course.'.$cid.'.home'};
                   6034:     }
                   6035:     if ($needsrelease) {
                   6036:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6037:         my $needsupdate;
                   6038:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6039:             $needsupdate = 1;
                   6040:         } else {
                   6041:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6042:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6043:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6044:                 $needsupdate = 1;
                   6045:             }
                   6046:         }
                   6047:         if ($needsupdate) {
                   6048:             my %needshash = (
                   6049:                              'internal.releaserequired' => $needsrelease,
                   6050:                             );
                   6051:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6052:             if ($putresult eq 'ok') {
                   6053:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6054:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6055:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6056:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6057:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6058:                 }
                   6059:             }
                   6060:         }
                   6061:     }
                   6062:     return;
                   6063: }
                   6064: 
1.461     www      6065: # -------------------------------------------------See if a user is privileged
                   6066: 
                   6067: sub privileged {
1.1172.2.23  raeburn  6068:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6069:     my $now = time;
1.1172.2.23  raeburn  6070:     my $roles;
                   6071:     if (ref($possroles) eq 'ARRAY') {
                   6072:         $roles = $possroles;
                   6073:     } else {
                   6074:         $roles = ['dc','su'];
                   6075:     }
                   6076:     if (ref($possdomains) eq 'ARRAY') {
                   6077:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6078:         foreach my $dom (@{$possdomains}) {
                   6079:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6080:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6081:                 foreach my $role (@{$roles}) {
                   6082:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6083:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6084:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6085:                             return 1 unless (($end && $end < $now) ||
                   6086:                                              ($start && $start > $now));
                   6087:                         }
                   6088:                     }
                   6089:                 }
                   6090:             }
                   6091:         }
                   6092:     } else {
                   6093:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6094:         my $now = time;
1.1170    droeschl 6095: 
1.1172.2.58  raeburn  6096:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6097:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6098:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6099:                 return 1 unless ($tend && $tend < $now)
                   6100:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6101:             }
1.1172.2.23  raeburn  6102:         }
                   6103:     }
1.461     www      6104:     return 0;
1.9       www      6105: }
1.1       albertel 6106: 
1.1172.2.23  raeburn  6107: sub privileged_by_domain {
                   6108:     my ($domains,$roles) = @_;
                   6109:     my %privileged = ();
                   6110:     my $cachetime = 60*60*24;
                   6111:     my $now = time;
                   6112:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6113:         return %privileged;
                   6114:     }
                   6115:     foreach my $dom (@{$domains}) {
                   6116:         next if (ref($privileged{$dom}) eq 'HASH');
                   6117:         my $needroles;
                   6118:         foreach my $role (@{$roles}) {
                   6119:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6120:             if (defined($cached)) {
                   6121:                 if (ref($result) eq 'HASH') {
                   6122:                     $privileged{$dom}{$role} = $result;
                   6123:                 }
                   6124:             } else {
                   6125:                 $needroles = 1;
                   6126:             }
                   6127:         }
                   6128:         if ($needroles) {
                   6129:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6130:             $privileged{$dom} = {};
                   6131:             foreach my $server (keys(%dompersonnel)) {
                   6132:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6133:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6134:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6135:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6136:                         next if ($end && $end < $now);
                   6137:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6138:                             $dompersonnel{$server}{$item};
                   6139:                     }
                   6140:                 }
                   6141:             }
                   6142:             if (ref($privileged{$dom}) eq 'HASH') {
                   6143:                 foreach my $role (@{$roles}) {
                   6144:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6145:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6146:                     } else {
                   6147:                         my %hash = ();
                   6148:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6149:                     }
                   6150:                 }
                   6151:             }
                   6152:         }
                   6153:     }
                   6154:     return %privileged;
                   6155: }
                   6156: 
1.103     harris41 6157: # -------------------------------------------------------- Get user privileges
1.11      www      6158: 
                   6159: sub rolesinit {
1.1169    droeschl 6160:     my ($domain, $username) = @_;
                   6161:     my %userroles = ('user.login.time' => time);
                   6162:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6163: 
                   6164:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6165:     # also, blocking can be triggered by an activating timer
                   6166:     # it's saved in the user's %env.
                   6167:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6168:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6169:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6170:         %timerintchk, %timerintenv);
                   6171: 
1.1162    raeburn  6172:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6173:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6174:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6175:     }
1.1169    droeschl 6176: 
1.1162    raeburn  6177:     foreach my $key (keys(%timerinterval)) {
                   6178:         my ($cid,$rest) = split(/\0/,$key);
                   6179:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6180:     }
1.1169    droeschl 6181: 
1.11      www      6182:     my %allroles=();
1.1162    raeburn  6183:     my %allgroups=();
1.11      www      6184: 
1.1172.2.58  raeburn  6185:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6186:         my $role = $rolesdump{$area};
                   6187:         $area =~ s/\_\w\w$//;
                   6188: 
                   6189:         my ($trole, $tend, $tstart, $group_privs);
                   6190: 
                   6191:         if ($role =~ /^cr/) {
                   6192:         # Custom role, defined by a user 
                   6193:         # e.g., user.role.cr/msu/smith/mynewrole
                   6194:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6195:                 $trole = $1;
                   6196:                 ($tend, $tstart) = split('_', $2);
                   6197:             } else {
                   6198:                 $trole = $role;
                   6199:             }
                   6200:         } elsif ($role =~ m|^gr/|) {
                   6201:         # Role of member in a group, defined within a course/community
                   6202:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6203:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6204:             next if $tstart eq '-1';
                   6205:             ($trole, $group_privs) = split(/\//, $trole);
                   6206:             $group_privs = &unescape($group_privs);
                   6207:         } else {
                   6208:         # Just a normal role, defined in roles.tab
                   6209:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6210:         }
                   6211: 
                   6212:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6213:                  $username);
                   6214:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6215: 
                   6216:         # role expired or not available yet?
                   6217:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6218:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6219: 
                   6220:         next if $area eq '' or $trole eq '';
                   6221: 
                   6222:         my $spec = "$trole.$area";
                   6223:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6224: 
                   6225:         if ($trole =~ /^cr\//) {
                   6226:         # Custom role, defined by a user
                   6227:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6228:         } elsif ($trole eq 'gr') {
                   6229:         # Role of a member in a group, defined within a course/community
                   6230:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6231:             next;
                   6232:         } else {
                   6233:         # Normal role, defined in roles.tab
                   6234:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6235:         }
                   6236: 
                   6237:         my $cid = $tdomain.'_'.$trest;
                   6238:         unless ($firstaccchk{$cid}) {
                   6239:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6240:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6241:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6242:                         $coursetimerstarts{$cid}{$item}; 
                   6243:                 }
                   6244:             }
                   6245:             $firstaccchk{$cid} = 1;
                   6246:         }
                   6247:         unless ($timerintchk{$cid}) {
                   6248:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6249:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6250:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6251:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6252:                 }
1.12      www      6253:             }
1.1169    droeschl 6254:             $timerintchk{$cid} = 1;
1.191     harris41 6255:         }
1.11      www      6256:     }
1.1169    droeschl 6257: 
1.1172.2.91  raeburn  6258:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6259:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6260:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6261:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6262: 
1.1162    raeburn  6263:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6264: }
                   6265: 
1.567     raeburn  6266: sub set_arearole {
1.1172.2.19  raeburn  6267:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6268:     unless ($nolog) {
1.567     raeburn  6269: # log the associated role with the area
1.1172.2.19  raeburn  6270:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6271:     }
1.743     albertel 6272:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6273: }
                   6274: 
                   6275: sub custom_roleprivs {
                   6276:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6277:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6278:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6279:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6280:         my ($rdummy,$roledef)=
                   6281:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6282:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6283:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6284:             if (defined($syspriv)) {
1.1043    raeburn  6285:                 if ($trest =~ /^$match_community$/) {
                   6286:                     $syspriv =~ s/bre\&S//; 
                   6287:                 }
1.567     raeburn  6288:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6289:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6290:             }
                   6291:             if ($tdomain ne '') {
                   6292:                 if (defined($dompriv)) {
                   6293:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6294:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6295:                 }
                   6296:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6297:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6298:                         my $rolename = $1;
                   6299:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6300:                     }
1.567     raeburn  6301:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6302:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6303:                 }
                   6304:             }
                   6305:         }
                   6306:     }
                   6307: }
                   6308: 
1.1172.2.89  raeburn  6309: sub course_adhocrole_privs {
                   6310:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6311:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6312:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6313:         my (%currprivs,%storeprivs);
                   6314:         foreach my $item (split(/:/,$coursepriv)) {
                   6315:             my ($priv,$restrict) = split(/\&/,$item);
                   6316:             $currprivs{$priv} = $restrict;
                   6317:         }
                   6318:         my (%possadd,%possremove,%full);
                   6319:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6320:             my ($priv,$restrict)=split(/\&/,$item);
                   6321:             $full{$priv} = $restrict;
                   6322:         }
                   6323:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6324:              next if ($item eq '');
                   6325:              my ($rule,$rest) = split(/=/,$item);
                   6326:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6327:              foreach my $priv (split(/:/,$rest)) {
                   6328:                  if ($priv ne '') {
                   6329:                      if ($rule eq 'off') {
                   6330:                          $possremove{$priv} = 1;
                   6331:                      } else {
                   6332:                          $possadd{$priv} = 1;
                   6333:                      }
                   6334:                  }
                   6335:              }
                   6336:          }
                   6337:          foreach my $priv (sort(keys(%full))) {
                   6338:              if (exists($currprivs{$priv})) {
                   6339:                  unless (exists($possremove{$priv})) {
                   6340:                      $storeprivs{$priv} = $currprivs{$priv};
                   6341:                  }
                   6342:              } elsif (exists($possadd{$priv})) {
                   6343:                  $storeprivs{$priv} = $full{$priv};
                   6344:              }
                   6345:          }
                   6346:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6347:      }
                   6348:      return $coursepriv;
                   6349: }
                   6350: 
1.678     raeburn  6351: sub group_roleprivs {
                   6352:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6353:     my $access = 1;
                   6354:     my $now = time;
                   6355:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6356:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6357:     if ($access) {
1.811     albertel 6358:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6359:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6360:     }
                   6361: }
1.567     raeburn  6362: 
                   6363: sub standard_roleprivs {
                   6364:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6365:     if (defined($pr{$trole.':s'})) {
                   6366:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6367:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6368:     }
                   6369:     if ($tdomain ne '') {
                   6370:         if (defined($pr{$trole.':d'})) {
                   6371:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6372:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6373:         }
                   6374:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6375:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6376:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6377:         }
                   6378:     }
                   6379: }
                   6380: 
                   6381: sub set_userprivs {
1.1064    raeburn  6382:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6383:     my $author=0;
                   6384:     my $adv=0;
1.1172.2.91  raeburn  6385:     my $rar=0;
1.678     raeburn  6386:     my %grouproles = ();
                   6387:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6388:         my @groupkeys; 
1.1000    raeburn  6389:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6390:             push(@groupkeys,$role);
                   6391:         }
                   6392:         if (ref($groups_roles) eq 'HASH') {
                   6393:             foreach my $key (keys(%{$groups_roles})) {
                   6394:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6395:                     push(@groupkeys,$key);
                   6396:                 }
                   6397:             }
                   6398:         }
                   6399:         if (@groupkeys > 0) {
                   6400:             foreach my $role (@groupkeys) {
                   6401:                 my ($trole,$area,$sec,$extendedarea);
                   6402:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6403:                     $trole = $1;
                   6404:                     $area = $2;
                   6405:                     $sec = $3;
                   6406:                     $extendedarea = $area.$sec;
                   6407:                     if (exists($$allgroups{$area})) {
                   6408:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6409:                             my $spec = $trole.'.'.$extendedarea;
                   6410:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6411:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6412:                         }
1.678     raeburn  6413:                     }
                   6414:                 }
                   6415:             }
                   6416:         }
                   6417:     }
1.800     albertel 6418:     foreach my $group (keys(%grouproles)) {
                   6419:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6420:     }
1.800     albertel 6421:     foreach my $role (keys(%{$allroles})) {
                   6422:         my %thesepriv;
1.941     raeburn  6423:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6424:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6425:             if ($item ne '') {
                   6426:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6427:                 if ($restrictions eq '') {
                   6428:                     $thesepriv{$privilege}='F';
                   6429:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6430:                     $thesepriv{$privilege}.=$restrictions;
                   6431:                 }
                   6432:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6433:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6434:             }
                   6435:         }
                   6436:         my $thesestr='';
1.1104    raeburn  6437:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6438: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6439: 	}
                   6440:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6441:     }
1.1172.2.91  raeburn  6442:     return ($author,$adv,$rar);
1.567     raeburn  6443: }
                   6444: 
1.994     raeburn  6445: sub role_status {
1.1104    raeburn  6446:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6447:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6448:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6449:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6450:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6451:             $$where = '/'.$two;
1.994     raeburn  6452:             $$trolecode=$$role.'.'.$$where;
                   6453:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6454:             $$tstatus='is';
1.1104    raeburn  6455:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6456:                 $$tstatus='future';
1.1034    raeburn  6457:                 if ($$tstart<$now) {
                   6458:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6459:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6460:                             my (%allroles,%allgroups,$group_privs,
                   6461:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6462:                             my %userroles = (
                   6463:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6464:                             );
1.1064    raeburn  6465:                             @rolecodes = ('cm'); 
1.1002    raeburn  6466:                             my $spec=$$role.'.'.$$where;
                   6467:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6468:                             if ($$role =~ /^cr\//) {
                   6469:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6470:                                 push(@rolecodes,'cr');
1.1002    raeburn  6471:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6472:                                 push(@rolecodes,$$role);
1.1002    raeburn  6473:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6474:                                                     $env{'user.name'});
1.1064    raeburn  6475:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6476:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6477:                                 $group_privs = &unescape($group_privs);
                   6478:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6479:                                 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  6480:                                 &get_groups_roles($tdomain,$trest,
                   6481:                                                   \%course_roles,\@rolecodes,
                   6482:                                                   \%groups_roles);
1.1002    raeburn  6483:                             } else {
1.1064    raeburn  6484:                                 push(@rolecodes,$$role);
1.1002    raeburn  6485:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6486:                             }
1.1172.2.91  raeburn  6487:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6488:                                                                    \%groups_roles);
1.1064    raeburn  6489:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6490:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6491:                         }
                   6492:                     }
1.1034    raeburn  6493:                     $$tstatus = 'is';
1.1002    raeburn  6494:                 }
1.994     raeburn  6495:             }
                   6496:             if ($$tend) {
1.1104    raeburn  6497:                 if ($$tend<$update) {
1.994     raeburn  6498:                     $$tstatus='expired';
                   6499:                 } elsif ($$tend<$now) {
                   6500:                     $$tstatus='will_not';
                   6501:                 }
                   6502:             }
                   6503:         }
                   6504:     }
                   6505: }
                   6506: 
1.1104    raeburn  6507: sub get_groups_roles {
                   6508:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6509:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6510:                   (ref($rolecodes) eq 'ARRAY') && 
                   6511:                   (ref($groups_roles) eq 'HASH')); 
                   6512:     if (keys(%{$cdom_courseroles}) > 0) {
                   6513:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6514:         if ($cdom ne '' && $cnum ne '') {
                   6515:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6516:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6517:                     my $crsrole = $1;
                   6518:                     my $crssec = $2;
                   6519:                     if ($crsrole =~ /^cr/) {
                   6520:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6521:                             push(@{$rolecodes},'cr');
                   6522:                         }
                   6523:                     } else {
                   6524:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6525:                             push(@{$rolecodes},$crsrole);
                   6526:                         }
                   6527:                     }
                   6528:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6529:                     if ($crssec ne '') {
                   6530:                         $rolekey .= "/$crssec";
                   6531:                     }
                   6532:                     $rolekey .= './';
                   6533:                     $groups_roles->{$rolekey} = $rolecodes;
                   6534:                 }
                   6535:             }
                   6536:         }
                   6537:     }
                   6538:     return;
                   6539: }
                   6540: 
                   6541: sub delete_env_groupprivs {
                   6542:     my ($where,$courseroles,$possroles) = @_;
                   6543:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6544:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6545:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6546:         %{$courseroles->{$udom}} =
                   6547:             &get_my_roles('','','userroles',['active'],
                   6548:                           $possroles,[$udom],1);
                   6549:     }
                   6550:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6551:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6552:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6553:             my $area = '/'.$cdom.'/'.$cnum;
                   6554:             my $privkey = "user.priv.$crsrole.$area";
                   6555:             if ($crssec ne '') {
                   6556:                 $privkey .= '/'.$crssec;
                   6557:             }
                   6558:             $privkey .= ".$area/$group";
                   6559:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6560:         }
                   6561:     }
                   6562:     return;
                   6563: }
                   6564: 
1.994     raeburn  6565: sub check_adhoc_privs {
1.1172.2.86  raeburn  6566:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6567:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6568:     if ($sec) {
                   6569:         $cckey .= '/'.$sec;
                   6570:     }
1.1172.2.9  raeburn  6571:     my $setprivs;
1.994     raeburn  6572:     if ($env{$cckey}) {
                   6573:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6574:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6575:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6576:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6577:             $setprivs = 1;
1.994     raeburn  6578:         }
                   6579:     } else {
1.1172.2.87  raeburn  6580:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6581:         $setprivs = 1;
1.994     raeburn  6582:     }
1.1172.2.9  raeburn  6583:     return $setprivs;
1.994     raeburn  6584: }
                   6585: 
                   6586: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6587: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6588:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6589:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6590:     if ($sec ne '') {
                   6591:         $area .= '/'.$sec;
                   6592:     }
1.994     raeburn  6593:     my $spec = $role.'.'.$area;
                   6594:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6595:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6596:     my %rolehash = ();
1.1172.2.89  raeburn  6597:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6598:         my $rolename = $1;
1.1172.2.84  raeburn  6599:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6600:         my %domdef = &get_domain_defaults($dcdom);
                   6601:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6602:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6603:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6604:             }
                   6605:         }
1.1172.2.84  raeburn  6606:     } else {
                   6607:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6608:     }
1.1172.2.91  raeburn  6609:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6610:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6611:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6612:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6613:         &appenv( {'request.role'        => $spec,
                   6614:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6615:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6616:                  }
                   6617:                );
                   6618:         my $tadv=0;
                   6619:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6620:         &appenv({'request.role.adv'    => $tadv});
                   6621:     }
1.994     raeburn  6622: }
                   6623: 
1.12      www      6624: # --------------------------------------------------------------- get interface
                   6625: 
                   6626: sub get {
1.131     albertel 6627:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6628:    my $items='';
1.800     albertel 6629:    foreach my $item (@$storearr) {
                   6630:        $items.=&escape($item).'&';
1.191     harris41 6631:    }
1.12      www      6632:    $items=~s/\&$//;
1.620     albertel 6633:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6634:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6635:    my $uhome=&homeserver($uname,$udomain);
                   6636: 
1.133     albertel 6637:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6638:    my @pairs=split(/\&/,$rep);
1.273     albertel 6639:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6640:      return @pairs;
                   6641:    }
1.15      www      6642:    my %returnhash=();
1.42      www      6643:    my $i=0;
1.800     albertel 6644:    foreach my $item (@$storearr) {
                   6645:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6646:       $i++;
1.191     harris41 6647:    }
1.15      www      6648:    return %returnhash;
1.27      www      6649: }
                   6650: 
                   6651: # --------------------------------------------------------------- del interface
                   6652: 
                   6653: sub del {
1.133     albertel 6654:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6655:    my $items='';
1.800     albertel 6656:    foreach my $item (@$storearr) {
                   6657:        $items.=&escape($item).'&';
1.191     harris41 6658:    }
1.984     neumanie 6659: 
1.27      www      6660:    $items=~s/\&$//;
1.620     albertel 6661:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6662:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6663:    my $uhome=&homeserver($uname,$udomain);
                   6664:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6665: }
                   6666: 
                   6667: # -------------------------------------------------------------- dump interface
                   6668: 
1.1172.2.22  raeburn  6669: sub unserialize {
                   6670:     my ($rep, $escapedkeys) = @_;
                   6671: 
                   6672:     return {} if $rep =~ /^error/;
                   6673: 
                   6674:     my %returnhash=();
                   6675:     foreach my $item (split(/\&/,$rep)) {
                   6676:         my ($key, $value) = split(/=/, $item, 2);
                   6677:         $key = unescape($key) unless $escapedkeys;
                   6678:         next if $key =~ /^error: 2 /;
                   6679:         $returnhash{$key} = &thaw_unescape($value);
                   6680:     }
                   6681:     return \%returnhash;
                   6682: }
                   6683: 
                   6684: # see Lond::dump_with_regexp
                   6685: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6686: sub dump {
1.1172.2.22  raeburn  6687:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6688:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6689:     if (!$uname) { $uname=$env{'user.name'}; }
                   6690:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6691: 
1.1172.2.55  raeburn  6692:     if ($regexp) {
                   6693:         $regexp=&escape($regexp);
                   6694:     } else {
                   6695:         $regexp='.';
                   6696:     }
1.1172.2.22  raeburn  6697:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6698:         # user is hosted on this machine
1.1172.2.55  raeburn  6699:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6700:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6701:         return %{&unserialize($reply, $escapedkeys)};
                   6702:     }
1.1166    raeburn  6703:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6704:     my @pairs=split(/\&/,$rep);
                   6705:     my %returnhash=();
1.1098    foxr     6706:     if (!($rep =~ /^error/ )) {
                   6707: 	foreach my $item (@pairs) {
                   6708: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6709:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6710: 	    next if ($key =~ /^error: 2 /);
                   6711: 	    $returnhash{$key}=&thaw_unescape($value);
                   6712: 	}
1.755     albertel 6713:     }
                   6714:     return %returnhash;
1.407     www      6715: }
                   6716: 
1.1098    foxr     6717: 
1.717     albertel 6718: # --------------------------------------------------------- dumpstore interface
                   6719: 
                   6720: sub dumpstore {
                   6721:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6722:    # same as dump but keys must be escaped. They may contain colon separated
                   6723:    # lists of values that may themself contain colons (e.g. symbs).
                   6724:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6725: }
                   6726: 
1.407     www      6727: # -------------------------------------------------------------- keys interface
                   6728: 
                   6729: sub getkeys {
                   6730:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6731:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6732:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6733:    my $uhome=&homeserver($uname,$udomain);
                   6734:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6735:    my @keyarray=();
1.800     albertel 6736:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6737:       next if ($key =~ /^error: 2 /);
1.800     albertel 6738:       push(@keyarray,&unescape($key));
1.407     www      6739:    }
                   6740:    return @keyarray;
1.318     matthew  6741: }
                   6742: 
1.319     matthew  6743: # --------------------------------------------------------------- currentdump
                   6744: sub currentdump {
1.328     matthew  6745:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6746:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6747:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6748:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6749:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6750:    my $rep;
                   6751: 
                   6752:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6753:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6754:                    $courseid)));
                   6755:    } else {
                   6756:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6757:    }
                   6758: 
1.318     matthew  6759:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6760:    #
1.318     matthew  6761:    my %returnhash=();
1.319     matthew  6762:    #
                   6763:    if ($rep eq "unknown_cmd") { 
                   6764:        # an old lond will not know currentdump
                   6765:        # Do a dump and make it look like a currentdump
1.822     albertel 6766:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6767:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6768:        my %hash = @tmp;
                   6769:        @tmp=();
1.424     matthew  6770:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6771:    } else {
                   6772:        my @pairs=split(/\&/,$rep);
1.800     albertel 6773:        foreach my $pair (@pairs) {
                   6774:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6775:            my ($symb,$param) = split(/:/,$key);
                   6776:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6777:                                                         &thaw_unescape($value);
1.319     matthew  6778:        }
1.191     harris41 6779:    }
1.12      www      6780:    return %returnhash;
1.424     matthew  6781: }
                   6782: 
                   6783: sub convert_dump_to_currentdump{
                   6784:     my %hash = %{shift()};
                   6785:     my %returnhash;
                   6786:     # Code ripped from lond, essentially.  The only difference
                   6787:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6788:     # we might run in to problems with parameter names =~ /^v\./
                   6789:     while (my ($key,$value) = each(%hash)) {
                   6790:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6791: 	$symb  = &unescape($symb);
                   6792: 	$param = &unescape($param);
1.424     matthew  6793:         next if ($v eq 'version' || $symb eq 'keys');
                   6794:         next if (exists($returnhash{$symb}) &&
                   6795:                  exists($returnhash{$symb}->{$param}) &&
                   6796:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6797:         $returnhash{$symb}->{$param}=$value;
                   6798:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6799:     }
                   6800:     #
                   6801:     # Remove all of the keys in the hashes which keep track of
                   6802:     # the version of the parameter.
                   6803:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6804:         # use a foreach because we are going to delete from the hash.
                   6805:         foreach my $key (keys(%$param_hash)) {
                   6806:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6807:         }
                   6808:     }
                   6809:     return \%returnhash;
1.12      www      6810: }
                   6811: 
1.627     albertel 6812: # ------------------------------------------------------ critical inc interface
                   6813: 
                   6814: sub cinc {
                   6815:     return &inc(@_,'critical');
                   6816: }
                   6817: 
1.449     matthew  6818: # --------------------------------------------------------------- inc interface
                   6819: 
                   6820: sub inc {
1.627     albertel 6821:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6822:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6823:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6824:     my $uhome=&homeserver($uname,$udomain);
                   6825:     my $items='';
                   6826:     if (! ref($store)) {
                   6827:         # got a single value, so use that instead
                   6828:         $items = &escape($store).'=&';
                   6829:     } elsif (ref($store) eq 'SCALAR') {
                   6830:         $items = &escape($$store).'=&';        
                   6831:     } elsif (ref($store) eq 'ARRAY') {
                   6832:         $items = join('=&',map {&escape($_);} @{$store});
                   6833:     } elsif (ref($store) eq 'HASH') {
                   6834:         while (my($key,$value) = each(%{$store})) {
                   6835:             $items.= &escape($key).'='.&escape($value).'&';
                   6836:         }
                   6837:     }
                   6838:     $items=~s/\&$//;
1.627     albertel 6839:     if ($critical) {
                   6840: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6841:     } else {
                   6842: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6843:     }
1.449     matthew  6844: }
                   6845: 
1.12      www      6846: # --------------------------------------------------------------- put interface
                   6847: 
                   6848: sub put {
1.134     albertel 6849:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6851:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6852:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6853:    my $items='';
1.800     albertel 6854:    foreach my $item (keys(%$storehash)) {
                   6855:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6856:    }
1.12      www      6857:    $items=~s/\&$//;
1.134     albertel 6858:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6859: }
                   6860: 
1.631     albertel 6861: # ------------------------------------------------------------ newput interface
                   6862: 
                   6863: sub newput {
                   6864:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6865:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6866:    if (!$uname) { $uname=$env{'user.name'}; }
                   6867:    my $uhome=&homeserver($uname,$udomain);
                   6868:    my $items='';
                   6869:    foreach my $key (keys(%$storehash)) {
                   6870:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6871:    }
                   6872:    $items=~s/\&$//;
                   6873:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6874: }
                   6875: 
                   6876: # ---------------------------------------------------------  putstore interface
                   6877: 
1.524     raeburn  6878: sub putstore {
1.1172.2.59  raeburn  6879:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6880:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6881:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6882:    my $uhome=&homeserver($uname,$udomain);
                   6883:    my $items='';
1.715     albertel 6884:    foreach my $key (keys(%$storehash)) {
                   6885:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6886:    }
1.715     albertel 6887:    $items=~s/\&$//;
1.716     albertel 6888:    my $esc_symb=&escape($symb);
                   6889:    my $esc_v=&escape($version);
1.715     albertel 6890:    my $reply =
1.716     albertel 6891:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6892: 	      $uhome);
1.1172.2.59  raeburn  6893:    if (($tolog) && ($reply eq 'ok')) {
                   6894:        my $namevalue='';
                   6895:        foreach my $key (keys(%{$storehash})) {
                   6896:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6897:        }
                   6898:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6899:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6900:                      '&version='.$esc_v.
                   6901:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6902:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6903:    }
1.715     albertel 6904:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6905:        # gfall back to way things use to be done
1.715     albertel 6906:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6907: 			    $uname);
1.524     raeburn  6908:    }
1.715     albertel 6909:    return $reply;
                   6910: }
                   6911: 
                   6912: sub old_putstore {
1.716     albertel 6913:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6914:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6915:     if (!$uname) { $uname=$env{'user.name'}; }
                   6916:     my $uhome=&homeserver($uname,$udomain);
                   6917:     my %newstorehash;
1.800     albertel 6918:     foreach my $item (keys(%$storehash)) {
                   6919: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6920: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6921:     }
                   6922:     my $items='';
                   6923:     my %allitems = ();
1.800     albertel 6924:     foreach my $item (keys(%newstorehash)) {
                   6925: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6926: 	    my $key = $1.':keys:'.$2;
                   6927: 	    $allitems{$key} .= $3.':';
                   6928: 	}
1.800     albertel 6929: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6930:     }
1.800     albertel 6931:     foreach my $item (keys(%allitems)) {
                   6932: 	$allitems{$item} =~ s/\:$//;
                   6933: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6934:     }
                   6935:     $items=~s/\&$//;
                   6936:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6937: }
                   6938: 
1.47      www      6939: # ------------------------------------------------------ critical put interface
                   6940: 
                   6941: sub cput {
1.134     albertel 6942:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6943:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6944:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6945:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6946:    my $items='';
1.800     albertel 6947:    foreach my $item (keys(%$storehash)) {
                   6948:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6949:    }
1.47      www      6950:    $items=~s/\&$//;
1.134     albertel 6951:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6952: }
                   6953: 
                   6954: # -------------------------------------------------------------- eget interface
                   6955: 
                   6956: sub eget {
1.133     albertel 6957:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6958:    my $items='';
1.800     albertel 6959:    foreach my $item (@$storearr) {
                   6960:        $items.=&escape($item).'&';
1.191     harris41 6961:    }
1.12      www      6962:    $items=~s/\&$//;
1.620     albertel 6963:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6964:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6965:    my $uhome=&homeserver($uname,$udomain);
                   6966:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6967:    my @pairs=split(/\&/,$rep);
                   6968:    my %returnhash=();
1.42      www      6969:    my $i=0;
1.800     albertel 6970:    foreach my $item (@$storearr) {
                   6971:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6972:       $i++;
1.191     harris41 6973:    }
1.12      www      6974:    return %returnhash;
                   6975: }
                   6976: 
1.667     albertel 6977: # ------------------------------------------------------------ tmpput interface
                   6978: sub tmpput {
1.802     raeburn  6979:     my ($storehash,$server,$context)=@_;
1.667     albertel 6980:     my $items='';
1.800     albertel 6981:     foreach my $item (keys(%$storehash)) {
                   6982: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6983:     }
                   6984:     $items=~s/\&$//;
1.802     raeburn  6985:     if (defined($context)) {
                   6986:         $items .= ':'.&escape($context);
                   6987:     }
1.667     albertel 6988:     return &reply("tmpput:$items",$server);
                   6989: }
                   6990: 
                   6991: # ------------------------------------------------------------ tmpget interface
                   6992: sub tmpget {
1.688     albertel 6993:     my ($token,$server)=@_;
                   6994:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6995:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6996:     my %returnhash;
1.1172.2.85  raeburn  6997:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6998:         return %returnhash;
                   6999:     }
1.667     albertel 7000:     foreach my $item (split(/\&/,$rep)) {
                   7001: 	my ($key,$value)=split(/=/,$item);
                   7002: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7003:     }
                   7004:     return %returnhash;
                   7005: }
                   7006: 
1.1113    raeburn  7007: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7008: sub tmpdel {
                   7009:     my ($token,$server)=@_;
                   7010:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7011:     return &reply("tmpdel:$token",$server);
                   7012: }
                   7013: 
1.1172.2.13  raeburn  7014: # ------------------------------------------------------------ get_timebased_id
                   7015: 
                   7016: sub get_timebased_id {
                   7017:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7018:         $maxtries) = @_;
                   7019:     my ($newid,$error,$dellock);
                   7020:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7021:         return ('','ok','invalid call to get suffix');
                   7022:     }
                   7023: 
                   7024: # set defaults for any optional args for which values were not supplied
                   7025:     if ($who eq '') {
                   7026:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7027:     }
                   7028:     if (!$locktries) {
                   7029:         $locktries = 3;
                   7030:     }
                   7031:     if (!$maxtries) {
                   7032:         $maxtries = 10;
                   7033:     }
                   7034: 
                   7035:     if (($cdom eq '') || ($cnum eq '')) {
                   7036:         if ($env{'request.course.id'}) {
                   7037:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7038:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7039:         }
                   7040:         if (($cdom eq '') || ($cnum eq '')) {
                   7041:             return ('','ok','call to get suffix not in course context');
                   7042:         }
                   7043:     }
                   7044: 
                   7045: # construct locking item
                   7046:     my $lockhash = {
                   7047:                       $prefix."\0".'locked_'.$keyid => $who,
                   7048:                    };
                   7049:     my $tries = 0;
                   7050: 
                   7051: # attempt to get lock on nohist_$namespace file
                   7052:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7053:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7054:         $tries ++;
                   7055:         sleep 1;
                   7056:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7057:     }
                   7058: 
                   7059: # attempt to get unique identifier, based on current timestamp
                   7060:     if ($gotlock eq 'ok') {
                   7061:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7062:         my $id = time;
                   7063:         $newid = $id;
1.1172.2.56  raeburn  7064:         if ($idtype eq 'addcode') {
                   7065:             $newid .= &sixnum_code();
                   7066:         }
1.1172.2.13  raeburn  7067:         my $idtries = 0;
                   7068:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7069:             if ($idtype eq 'concat') {
                   7070:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7071:             } elsif ($idtype eq 'addcode') {
                   7072:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7073:             } else {
                   7074:                 $newid ++;
                   7075:             }
                   7076:             $idtries ++;
                   7077:         }
                   7078:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7079:             my %new_item =  (
                   7080:                               $prefix."\0".$newid => $who,
                   7081:                             );
                   7082:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7083:                                                  $cdom,$cnum);
                   7084:             if ($putresult ne 'ok') {
                   7085:                 undef($newid);
                   7086:                 $error = 'error saving new item: '.$putresult;
                   7087:             }
                   7088:         } else {
1.1172.2.56  raeburn  7089:              undef($newid);
1.1172.2.13  raeburn  7090:              $error = ('error: no unique suffix available for the new item ');
                   7091:         }
                   7092: #  remove lock
                   7093:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7094:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7095:     } else {
                   7096:         $error = "error: could not obtain lockfile\n";
                   7097:         $dellock = 'ok';
1.1172.2.58  raeburn  7098:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7099:             $dellock = 'nolock';
                   7100:         }
1.1172.2.13  raeburn  7101:     }
                   7102:     return ($newid,$dellock,$error);
                   7103: }
                   7104: 
1.1172.2.56  raeburn  7105: sub sixnum_code {
                   7106:     my $code;
                   7107:     for (0..6) {
                   7108:         $code .= int( rand(9) );
                   7109:     }
                   7110:     return $code;
                   7111: }
                   7112: 
1.765     albertel 7113: # -------------------------------------------------- portfolio access checking
                   7114: 
                   7115: sub portfolio_access {
1.1172.2.77  raeburn  7116:     my ($requrl,$clientip) = @_;
1.765     albertel 7117:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7118:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7119:     if ($result) {
                   7120:         my %setters;
                   7121:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7122:             my ($startblock,$endblock) =
                   7123:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7124:             if ($startblock && $endblock) {
                   7125:                 return 'B';
                   7126:             }
                   7127:         } else {
                   7128:             my ($startblock,$endblock) =
                   7129:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7130:             if ($startblock && $endblock) {
                   7131:                 return 'B';
                   7132:             }
                   7133:         }
                   7134:     }
1.765     albertel 7135:     if ($result eq 'ok') {
1.766     albertel 7136:        return 'F';
1.765     albertel 7137:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7138:        return 'A';
1.765     albertel 7139:     }
1.766     albertel 7140:     return '';
1.765     albertel 7141: }
                   7142: 
                   7143: sub get_portfolio_access {
1.1172.2.77  raeburn  7144:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7145: 
                   7146:     if (!ref($access_hash)) {
                   7147: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7148: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7149: 						   $file_name);
                   7150: 	$access_hash = $access_controls{$file_name};
                   7151:     }
                   7152: 
1.1172.2.77  raeburn  7153:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7154:     my $now = time;
                   7155:     if (ref($access_hash) eq 'HASH') {
                   7156:         foreach my $key (keys(%{$access_hash})) {
                   7157:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7158:             if ($start > $now) {
                   7159:                 next;
                   7160:             }
                   7161:             if ($end && $end<$now) {
                   7162:                 next;
                   7163:             }
                   7164:             if ($scope eq 'public') {
                   7165:                 $public = $key;
                   7166:                 last;
                   7167:             } elsif ($scope eq 'guest') {
                   7168:                 $guest = $key;
                   7169:             } elsif ($scope eq 'domains') {
                   7170:                 push(@domains,$key);
                   7171:             } elsif ($scope eq 'users') {
                   7172:                 push(@users,$key);
                   7173:             } elsif ($scope eq 'course') {
                   7174:                 push(@courses,$key);
                   7175:             } elsif ($scope eq 'group') {
                   7176:                 push(@groups,$key);
1.1172.2.77  raeburn  7177:             } elsif ($scope eq 'ip') {
                   7178:                 push(@ips,$key);
1.765     albertel 7179:             }
                   7180:         }
                   7181:         if ($public) {
                   7182:             return 'ok';
1.1172.2.77  raeburn  7183:         } elsif (@ips > 0) {
                   7184:             my $allowed;
                   7185:             foreach my $ipkey (@ips) {
                   7186:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7187:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7188:                         $allowed = 1;
                   7189:                         last;
                   7190:                     }
                   7191:                 }
                   7192:             }
                   7193:             if ($allowed) {
                   7194:                 return 'ok';
                   7195:             }
1.765     albertel 7196:         }
                   7197:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7198:             if ($guest) {
                   7199:                 return $guest;
                   7200:             }
                   7201:         } else {
                   7202:             if (@domains > 0) {
                   7203:                 foreach my $domkey (@domains) {
                   7204:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7205:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7206:                             return 'ok';
                   7207:                         }
                   7208:                     }
                   7209:                 }
                   7210:             }
                   7211:             if (@users > 0) {
                   7212:                 foreach my $userkey (@users) {
1.865     raeburn  7213:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7214:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7215:                             if (ref($item) eq 'HASH') {
                   7216:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7217:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7218:                                     return 'ok';
                   7219:                                 }
                   7220:                             }
                   7221:                         }
                   7222:                     } 
1.765     albertel 7223:                 }
                   7224:             }
                   7225:             my %roleshash;
                   7226:             my @courses_and_groups = @courses;
                   7227:             push(@courses_and_groups,@groups); 
                   7228:             if (@courses_and_groups > 0) {
                   7229:                 my (%allgroups,%allroles); 
                   7230:                 my ($start,$end,$role,$sec,$group);
                   7231:                 foreach my $envkey (%env) {
1.1060    raeburn  7232:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7233:                         my $cid = $2.'_'.$3; 
                   7234:                         if ($1 eq 'gr') {
                   7235:                             $group = $4;
                   7236:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7237:                         } else {
                   7238:                             if ($4 eq '') {
                   7239:                                 $sec = 'none';
                   7240:                             } else {
                   7241:                                 $sec = $4;
                   7242:                             }
                   7243:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7244:                         }
1.811     albertel 7245:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7246:                         my $cid = $2.'_'.$3;
                   7247:                         if ($4 eq '') {
                   7248:                             $sec = 'none';
                   7249:                         } else {
                   7250:                             $sec = $4;
                   7251:                         }
                   7252:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7253:                     }
                   7254:                 }
                   7255:                 if (keys(%allroles) == 0) {
                   7256:                     return;
                   7257:                 }
                   7258:                 foreach my $key (@courses_and_groups) {
                   7259:                     my %content = %{$$access_hash{$key}};
                   7260:                     my $cnum = $content{'number'};
                   7261:                     my $cdom = $content{'domain'};
                   7262:                     my $cid = $cdom.'_'.$cnum;
                   7263:                     if (!exists($allroles{$cid})) {
                   7264:                         next;
                   7265:                     }    
                   7266:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7267:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7268:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7269:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7270:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7271:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7272:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7273:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7274:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7275:                                         if (grep/^all$/,@sections) {
                   7276:                                             return 'ok';
                   7277:                                         } else {
                   7278:                                             if (grep/^$sec$/,@sections) {
                   7279:                                                 return 'ok';
                   7280:                                             }
                   7281:                                         }
                   7282:                                     }
                   7283:                                 }
                   7284:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7285:                                     if (grep/^none$/,@groups) {
                   7286:                                         return 'ok';
                   7287:                                     }
                   7288:                                 } else {
                   7289:                                     if (grep/^all$/,@groups) {
                   7290:                                         return 'ok';
                   7291:                                     } 
                   7292:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7293:                                         if (grep/^$group$/,@groups) {
                   7294:                                             return 'ok';
                   7295:                                         }
                   7296:                                     }
                   7297:                                 } 
                   7298:                             }
                   7299:                         }
                   7300:                     }
                   7301:                 }
                   7302:             }
                   7303:             if ($guest) {
                   7304:                 return $guest;
                   7305:             }
                   7306:         }
                   7307:     }
                   7308:     return;
                   7309: }
                   7310: 
                   7311: sub course_group_datechecker {
                   7312:     my ($dates,$now,$status) = @_;
                   7313:     my ($start,$end) = split(/\./,$dates);
                   7314:     if (!$start && !$end) {
                   7315:         return 'ok';
                   7316:     }
                   7317:     if (grep/^active$/,@{$status}) {
                   7318:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7319:             return 'ok';
                   7320:         }
                   7321:     }
                   7322:     if (grep/^previous$/,@{$status}) {
                   7323:         if ($end > $now ) {
                   7324:             return 'ok';
                   7325:         }
                   7326:     }
                   7327:     if (grep/^future$/,@{$status}) {
                   7328:         if ($start > $now) {
                   7329:             return 'ok';
                   7330:         }
                   7331:     }
                   7332:     return; 
                   7333: }
                   7334: 
                   7335: sub parse_portfolio_url {
                   7336:     my ($url) = @_;
                   7337: 
                   7338:     my ($type,$udom,$unum,$group,$file_name);
                   7339:     
1.823     albertel 7340:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7341: 	$type = 1;
                   7342:         $udom = $1;
                   7343:         $unum = $2;
                   7344:         $file_name = $3;
1.823     albertel 7345:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7346: 	$type = 2;
                   7347:         $udom = $1;
                   7348:         $unum = $2;
                   7349:         $group = $3;
                   7350:         $file_name = $3.'/'.$4;
                   7351:     }
                   7352:     if (wantarray) {
                   7353: 	return ($type,$udom,$unum,$file_name,$group);
                   7354:     }
                   7355:     return $type;
                   7356: }
                   7357: 
                   7358: sub is_portfolio_url {
                   7359:     my ($url) = @_;
                   7360:     return scalar(&parse_portfolio_url($url));
                   7361: }
                   7362: 
1.798     raeburn  7363: sub is_portfolio_file {
                   7364:     my ($file) = @_;
1.820     raeburn  7365:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7366:         return 1;
                   7367:     }
                   7368:     return;
                   7369: }
                   7370: 
1.976     raeburn  7371: sub usertools_access {
1.1084    raeburn  7372:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7373:     my ($access,%tools);
                   7374:     if ($context eq '') {
                   7375:         $context = 'tools';
                   7376:     }
                   7377:     if ($context eq 'requestcourses') {
                   7378:         %tools = (
                   7379:                       official   => 1,
                   7380:                       unofficial => 1,
1.1006    raeburn  7381:                       community  => 1,
1.1172.2.37  raeburn  7382:                       textbook   => 1,
1.985     raeburn  7383:                  );
1.1172.2.9  raeburn  7384:     } elsif ($context eq 'requestauthor') {
                   7385:         %tools = (
                   7386:                       requestauthor => 1,
                   7387:                  );
1.985     raeburn  7388:     } else {
                   7389:         %tools = (
                   7390:                       aboutme   => 1,
                   7391:                       blog      => 1,
1.1172.2.6  raeburn  7392:                       webdav    => 1,
1.985     raeburn  7393:                       portfolio => 1,
                   7394:                  );
                   7395:     }
1.976     raeburn  7396:     return if (!defined($tools{$tool}));
                   7397: 
1.1172.2.35  raeburn  7398:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7399:         $udom = $env{'user.domain'};
                   7400:         $uname = $env{'user.name'};
                   7401:     }
                   7402: 
1.978     raeburn  7403:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7404:         if ($action ne 'reload') {
1.985     raeburn  7405:             if ($context eq 'requestcourses') {
                   7406:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7407:             } elsif ($context eq 'requestauthor') {
                   7408:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7409:             } else {
                   7410:                 return $env{'environment.availabletools.'.$tool};
                   7411:             }
                   7412:         }
1.976     raeburn  7413:     }
                   7414: 
1.1172.2.9  raeburn  7415:     my ($toolstatus,$inststatus,$envkey);
                   7416:     if ($context eq 'requestauthor') {
                   7417:         $envkey = $context;
                   7418:     } else {
                   7419:         $envkey = $context.'.'.$tool;
                   7420:     }
1.976     raeburn  7421: 
1.985     raeburn  7422:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7423:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7424:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7425:         $inststatus = $env{'environment.inststatus'};
                   7426:     } else {
1.1084    raeburn  7427:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7428:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7429:             $inststatus = $userenvref->{'inststatus'};
                   7430:         } else {
1.1172.2.9  raeburn  7431:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7432:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7433:             $inststatus = $userenv{'inststatus'};
                   7434:         }
1.976     raeburn  7435:     }
                   7436: 
                   7437:     if ($toolstatus ne '') {
                   7438:         if ($toolstatus) {
                   7439:             $access = 1;
                   7440:         } else {
                   7441:             $access = 0;
                   7442:         }
                   7443:         return $access;
                   7444:     }
                   7445: 
1.1084    raeburn  7446:     my ($is_adv,%domdef);
                   7447:     if (ref($is_advref) eq 'HASH') {
                   7448:         $is_adv = $is_advref->{'is_adv'};
                   7449:     } else {
                   7450:         $is_adv = &is_advanced_user($udom,$uname);
                   7451:     }
                   7452:     if (ref($domdefref) eq 'HASH') {
                   7453:         %domdef = %{$domdefref};
                   7454:     } else {
                   7455:         %domdef = &get_domain_defaults($udom);
                   7456:     }
1.976     raeburn  7457:     if (ref($domdef{$tool}) eq 'HASH') {
                   7458:         if ($is_adv) {
                   7459:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7460:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7461:                     $access = 1;
                   7462:                 } else {
                   7463:                     $access = 0;
                   7464:                 }
                   7465:                 return $access;
                   7466:             }
                   7467:         }
                   7468:         if ($inststatus ne '') {
                   7469:             my ($hasaccess,$hasnoaccess);
                   7470:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7471:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7472:                     if ($domdef{$tool}{$affiliation}) {
                   7473:                         $hasaccess = 1;
                   7474:                     } else {
                   7475:                         $hasnoaccess = 1;
                   7476:                     }
                   7477:                 }
                   7478:             }
                   7479:             if ($hasaccess || $hasnoaccess) {
                   7480:                 if ($hasaccess) {
                   7481:                     $access = 1;
                   7482:                 } elsif ($hasnoaccess) {
                   7483:                     $access = 0; 
                   7484:                 }
                   7485:                 return $access;
                   7486:             }
                   7487:         } else {
                   7488:             if ($domdef{$tool}{'default'} ne '') {
                   7489:                 if ($domdef{$tool}{'default'}) {
                   7490:                     $access = 1;
                   7491:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7492:                     $access = 0;
                   7493:                 }
                   7494:                 return $access;
                   7495:             }
                   7496:         }
                   7497:     } else {
1.1172.2.6  raeburn  7498:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7499:             $access = 1;
                   7500:         } else {
                   7501:             $access = 0;
                   7502:         }
1.976     raeburn  7503:         return $access;
                   7504:     }
                   7505: }
                   7506: 
1.1050    raeburn  7507: sub is_course_owner {
                   7508:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7509:     if (($udom eq '') || ($uname eq '')) {
                   7510:         $udom = $env{'user.domain'};
                   7511:         $uname = $env{'user.name'};
                   7512:     }
                   7513:     unless (($udom eq '') || ($uname eq '')) {
                   7514:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7515:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7516:                 return 1;
                   7517:             } else {
                   7518:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7519:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7520:                     return 1;
                   7521:                 }
                   7522:             }
                   7523:         }
                   7524:     }
                   7525:     return;
                   7526: }
                   7527: 
1.976     raeburn  7528: sub is_advanced_user {
                   7529:     my ($udom,$uname) = @_;
1.1085    raeburn  7530:     if ($udom ne '' && $uname ne '') {
                   7531:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7532:             if (wantarray) {
                   7533:                 return ($env{'user.adv'},$env{'user.author'});
                   7534:             } else {
                   7535:                 return $env{'user.adv'};
                   7536:             }
1.1085    raeburn  7537:         }
                   7538:     }
1.976     raeburn  7539:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7540:     my %allroles;
1.1128    raeburn  7541:     my ($is_adv,$is_author);
1.976     raeburn  7542:     foreach my $role (keys(%roleshash)) {
                   7543:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7544:         my $area = '/'.$tdomain.'/'.$trest;
                   7545:         if ($sec ne '') {
                   7546:             $area .= '/'.$sec;
                   7547:         }
                   7548:         if (($area ne '') && ($trole ne '')) {
                   7549:             my $spec=$trole.'.'.$area;
                   7550:             if ($trole =~ /^cr\//) {
                   7551:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7552:             } elsif ($trole ne 'gr') {
                   7553:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7554:             }
1.1128    raeburn  7555:             if ($trole eq 'au') {
                   7556:                 $is_author = 1;
                   7557:             }
1.976     raeburn  7558:         }
                   7559:     }
                   7560:     foreach my $role (keys(%allroles)) {
                   7561:         last if ($is_adv);
                   7562:         foreach my $item (split(/:/,$allroles{$role})) {
                   7563:             if ($item ne '') {
                   7564:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7565:                 if ($privilege eq 'adv') {
                   7566:                     $is_adv = 1;
                   7567:                     last;
                   7568:                 }
                   7569:             }
                   7570:         }
                   7571:     }
1.1128    raeburn  7572:     if (wantarray) {
                   7573:         return ($is_adv,$is_author);
                   7574:     }
1.976     raeburn  7575:     return $is_adv;
                   7576: }
1.798     raeburn  7577: 
1.1035    raeburn  7578: sub check_can_request {
1.1036    raeburn  7579:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7580:     my $canreq = 0;
                   7581:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7582:     my @options = ('approval','validate','autolimit');
                   7583:     my $optregex = join('|',@options);
                   7584:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7585:         foreach my $type (@{$types}) {
                   7586:             if (&usertools_access($env{'user.name'},
                   7587:                                   $env{'user.domain'},
                   7588:                                   $type,undef,'requestcourses')) {
                   7589:                 $canreq ++;
1.1036    raeburn  7590:                 if (ref($request_domains) eq 'HASH') {
                   7591:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7592:                 }
1.1035    raeburn  7593:                 if ($dom eq $env{'user.domain'}) {
                   7594:                     $can_request->{$type} = 1;
                   7595:                 }
                   7596:             }
                   7597:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7598:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7599:                 if (@curr > 0) {
1.1036    raeburn  7600:                     foreach my $item (@curr) {
                   7601:                         if (ref($request_domains) eq 'HASH') {
                   7602:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7603:                             if ($otherdom ne '') {
                   7604:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7605:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7606:                                         push(@{$request_domains->{$type}},$otherdom);
                   7607:                                     }
                   7608:                                 } else {
                   7609:                                     push(@{$request_domains->{$type}},$otherdom);
                   7610:                                 }
                   7611:                             }
                   7612:                         }
                   7613:                     }
                   7614:                     unless($dom eq $env{'user.domain'}) {
                   7615:                         $canreq ++;
1.1035    raeburn  7616:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7617:                             $can_request->{$type} = 1;
                   7618:                         }
                   7619:                     }
                   7620:                 }
                   7621:             }
                   7622:         }
                   7623:     }
                   7624:     return $canreq;
                   7625: }
                   7626: 
1.341     www      7627: # ---------------------------------------------- Custom access rule evaluation
                   7628: 
                   7629: sub customaccess {
                   7630:     my ($priv,$uri)=@_;
1.807     albertel 7631:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7632:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7633:     $udom = &LONCAPA::clean_domain($udom);
                   7634:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7635:     my $access=0;
1.800     albertel 7636:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7637: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7638: 	if ($type eq 'user') {
                   7639: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7640: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7641: 		if ($tdom) {
                   7642: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7643: 		}
1.896     albertel 7644: 		if ($tuname) {
                   7645: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7646: 		}
                   7647: 		$access=($effect eq 'allow');
                   7648: 		last;
                   7649: 	    }
                   7650: 	} else {
                   7651: 	    if ($role) {
                   7652: 		if ($role ne $urole) { next; }
                   7653: 	    }
                   7654: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7655: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7656: 		if ($tdom) {
                   7657: 		    if ($tdom ne $udom) { next; }
                   7658: 		}
                   7659: 		if ($tcrs) {
                   7660: 		    if ($tcrs ne $ucrs) { next; }
                   7661: 		}
                   7662: 		if ($tsec) {
                   7663: 		    if ($tsec ne $usec) { next; }
                   7664: 		}
                   7665: 		$access=($effect eq 'allow');
                   7666: 		last;
                   7667: 	    }
                   7668: 	    if ($realm eq '' && $role eq '') {
                   7669: 		$access=($effect eq 'allow');
                   7670: 	    }
1.402     bowersj2 7671: 	}
1.341     www      7672:     }
                   7673:     return $access;
                   7674: }
                   7675: 
1.103     harris41 7676: # ------------------------------------------------- Check for a user privilege
1.12      www      7677: 
                   7678: sub allowed {
1.1172.2.65  raeburn  7679:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7680:     my $ver_orguri=$uri;
1.439     www      7681:     $uri=&deversion($uri);
1.152     www      7682:     my $orguri=$uri;
1.52      www      7683:     $uri=&declutter($uri);
1.809     raeburn  7684: 
1.810     raeburn  7685:     if ($priv eq 'evb') {
                   7686: # Evade communication block restrictions for specified role in a course
                   7687:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7688:             return $1;
                   7689:         } else {
                   7690:             return;
                   7691:         }
                   7692:     }
                   7693: 
1.620     albertel 7694:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7695: # Free bre access to adm and meta resources
1.775     albertel 7696:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7697: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7698: 	&& ($priv eq 'bre')) {
1.14      www      7699: 	return 'F';
1.159     www      7700:     }
                   7701: 
1.545     banghart 7702: # Free bre access to user's own portfolio contents
1.714     raeburn  7703:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7704:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7705: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7706:         my %setters;
                   7707:         my ($startblock,$endblock) = 
                   7708:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7709:         if ($startblock && $endblock) {
                   7710:             return 'B';
                   7711:         } else {
                   7712:             return 'F';
                   7713:         }
1.545     banghart 7714:     }
                   7715: 
1.762     raeburn  7716: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7717:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7718:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7719:         if (exists($env{'request.course.id'})) {
                   7720:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7721:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7722:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7723:                 my $courseprivid=$env{'request.course.id'};
                   7724:                 $courseprivid=~s/\_/\//;
                   7725:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7726:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7727:                     return $1; 
1.762     raeburn  7728:                 } else {
                   7729:                     if ($env{'request.course.sec'}) {
                   7730:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7731:                     }
                   7732:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7733:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7734:                         return $2;
                   7735:                     }
1.714     raeburn  7736:                 }
                   7737:             }
                   7738:         }
                   7739:     }
                   7740: 
1.159     www      7741: # Free bre to public access
                   7742: 
                   7743:     if ($priv eq 'bre') {
1.238     www      7744:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7745: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7746:            return 'F'; 
                   7747:         }
1.238     www      7748:         if ($copyright eq 'priv') {
                   7749:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7750: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7751: 		return '';
                   7752:             }
                   7753:         }
                   7754:         if ($copyright eq 'domain') {
                   7755:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7756: 	    unless (($env{'user.domain'} eq $1) ||
                   7757:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7758: 		return '';
                   7759:             }
1.262     matthew  7760:         }
1.620     albertel 7761:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7762:             # Library role, so allow browsing of resources in this domain.
                   7763:             return 'F';
1.238     www      7764:         }
1.341     www      7765:         if ($copyright eq 'custom') {
                   7766: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7767:         }
1.14      www      7768:     }
1.264     matthew  7769:     # Domain coordinator is trying to create a course
1.620     albertel 7770:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7771:         # uri is the requested domain in this case.
                   7772:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7773:         # a role of dc for the domain in question.
1.620     albertel 7774:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7775:     }
1.29      www      7776: 
1.52      www      7777:     my $thisallowed='';
                   7778:     my $statecond=0;
                   7779:     my $courseprivid='';
                   7780: 
1.1039    raeburn  7781:     my $ownaccess;
1.1043    raeburn  7782:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7783:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7784:         if ($uri eq '') {
                   7785:             $ownaccess = 1;
                   7786:         } else {
                   7787:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7788:                 my $udom = $env{'user.domain'};
                   7789:                 my $uname = $env{'user.name'};
                   7790:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7791:                     $ownaccess = 1;
1.1040    raeburn  7792:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7793:                     unless ($uri =~ m{\.\./}) {
                   7794:                         $ownaccess = 1;
                   7795:                     }
                   7796:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7797:                     my $now = time;
                   7798:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7799:                         my $adom = $1;
                   7800:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7801:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7802:                                 my ($start,$end) = split('.',$env{$key});
                   7803:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7804:                                     $ownaccess = 1;
                   7805:                                     last;
                   7806:                                 }
                   7807:                             }
                   7808:                         }
                   7809:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7810:                         my $adom = $1;
                   7811:                         my $aname = $2;
1.1042    raeburn  7812:                         foreach my $role ('ca','aa') { 
                   7813:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7814:                                 my ($start,$end) =
                   7815:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7816:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7817:                                     $ownaccess = 1;
                   7818:                                     last;
                   7819:                                 }
1.1039    raeburn  7820:                             }
                   7821:                         }
                   7822:                     }
                   7823:                 }
                   7824:             }
                   7825:         }
                   7826:     }
                   7827: 
1.52      www      7828: # Course
                   7829: 
1.620     albertel 7830:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7831:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7832:             $thisallowed.=$1;
                   7833:         }
1.52      www      7834:     }
1.29      www      7835: 
1.52      www      7836: # Domain
                   7837: 
1.620     albertel 7838:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7839:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7840:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7841:             $thisallowed.=$1;
                   7842:         }
1.12      www      7843:     }
1.52      www      7844: 
1.1141    raeburn  7845: # User who is not author or co-author might still be able to edit
                   7846: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7847:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7848:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7849:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7850:             $thisallowed.=$1;
                   7851:         }
                   7852:     }
                   7853: 
1.52      www      7854: # Course: uri itself is a course
1.66      www      7855:     my $courseuri=$uri;
                   7856:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7857:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7858: 
1.620     albertel 7859:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7860:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7861:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7862:             $thisallowed.=$1;
                   7863:         }
1.12      www      7864:     }
1.29      www      7865: 
1.665     albertel 7866: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7867: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7868:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7869: 	$thisallowed='';
1.671     raeburn  7870:         my ($match)=&is_on_map($uri);
                   7871:         if ($match) {
                   7872:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7873:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7874:                 my $value = $1;
                   7875:                 if ($noblockcheck) {
                   7876:                     $thisallowed.=$value;
1.1162    raeburn  7877:                 } else {
1.1172.2.65  raeburn  7878:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7879:                     if (@blockers > 0) {
                   7880:                         $thisallowed = 'B';
                   7881:                     } else {
                   7882:                         $thisallowed.=$value;
                   7883:                     }
1.1162    raeburn  7884:                 }
1.671     raeburn  7885:             }
                   7886:         } else {
1.705     albertel 7887:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7888:             if ($refuri) {
                   7889:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7890:                     $thisallowed='F';
1.671     raeburn  7891:                 } else {
                   7892:                     $refuri=&declutter($refuri);
                   7893:                     my ($match) = &is_on_map($refuri);
                   7894:                     if ($match) {
1.1172.2.65  raeburn  7895:                         if ($noblockcheck) {
1.1162    raeburn  7896:                             $thisallowed='F';
1.1172.2.65  raeburn  7897:                         } else {
                   7898:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7899:                             if (@blockers > 0) {
                   7900:                                 $thisallowed = 'B';
                   7901:                             } else {
                   7902:                                 $thisallowed='F';
                   7903:                             }
1.1162    raeburn  7904:                         }
1.671     raeburn  7905:                     }
1.669     raeburn  7906:                 }
1.671     raeburn  7907:             }
                   7908:         }
1.314     www      7909:     }
1.492     albertel 7910: 
1.766     albertel 7911:     if ($priv eq 'bre'
                   7912: 	&& $thisallowed ne 'F' 
                   7913: 	&& $thisallowed ne '2'
                   7914: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7915: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7916:     }
                   7917:     
1.52      www      7918: # Full access at system, domain or course-wide level? Exit.
1.29      www      7919:     if ($thisallowed=~/F/) {
                   7920: 	return 'F';
                   7921:     }
                   7922: 
1.52      www      7923: # If this is generating or modifying users, exit with special codes
1.29      www      7924: 
1.643     www      7925:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7926: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7927: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7928: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7929: 	    unless ($auname) { return $thisallowed; }
                   7930: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7931: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7932: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7933: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7934: 	}
1.52      www      7935: 	return $thisallowed;
                   7936:     }
                   7937: #
1.103     harris41 7938: # Gathered so far: system, domain and course wide privileges
1.52      www      7939: #
                   7940: # Course: See if uri or referer is an individual resource that is part of 
                   7941: # the course
                   7942: 
1.620     albertel 7943:     if ($env{'request.course.id'}) {
1.232     www      7944: 
1.620     albertel 7945:        $courseprivid=$env{'request.course.id'};
                   7946:        if ($env{'request.course.sec'}) {
                   7947:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7948:        }
                   7949:        $courseprivid=~s/\_/\//;
                   7950:        my $checkreferer=1;
1.232     www      7951:        my ($match,$cond)=&is_on_map($uri);
                   7952:        if ($match) {
                   7953:            $statecond=$cond;
1.620     albertel 7954:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7955:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7956:                my $value = $1;
                   7957:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7958:                    if ($noblockcheck) {
1.1162    raeburn  7959:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7960:                    } else {
                   7961:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7962:                        if (@blockers > 0) {
                   7963:                            $thisallowed = 'B';
                   7964:                        } else {
                   7965:                            $thisallowed.=$value;
                   7966:                        }
1.1162    raeburn  7967:                    }
                   7968:                } else {
                   7969:                    $thisallowed.=$value;
                   7970:                }
1.52      www      7971:                $checkreferer=0;
                   7972:            }
1.29      www      7973:        }
1.83      www      7974:        
1.148     www      7975:        if ($checkreferer) {
1.620     albertel 7976: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7977:             unless ($refuri) {
1.800     albertel 7978:                 foreach my $key (keys(%env)) {
                   7979: 		    if ($key=~/^httpref\..*\*/) {
                   7980: 			my $pattern=$key;
1.156     www      7981:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7982:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7983:                         $pattern=~s/\//\\\//g;
1.152     www      7984:                         if ($orguri=~/$pattern/) {
1.800     albertel 7985: 			    $refuri=$env{$key};
1.148     www      7986:                         }
                   7987:                     }
1.191     harris41 7988:                 }
1.148     www      7989:             }
1.232     www      7990: 
1.148     www      7991:          if ($refuri) { 
1.152     www      7992: 	  $refuri=&declutter($refuri);
1.232     www      7993:           my ($match,$cond)=&is_on_map($refuri);
                   7994:             if ($match) {
                   7995:               my $refstatecond=$cond;
1.620     albertel 7996:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7997:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7998:                   my $value = $1;
                   7999:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8000:                       if ($noblockcheck) {
1.1162    raeburn  8001:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8002:                       } else {
                   8003:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8004:                           if (@blockers > 0) {
                   8005:                               $thisallowed = 'B';
                   8006:                           } else {
                   8007:                               $thisallowed.=$value;
                   8008:                           }
1.1162    raeburn  8009:                       }
                   8010:                   } else {
                   8011:                       $thisallowed.=$value;
                   8012:                   }
1.53      www      8013:                   $uri=$refuri;
                   8014:                   $statecond=$refstatecond;
1.52      www      8015:               }
                   8016:           }
1.148     www      8017:         }
1.29      www      8018:        }
1.52      www      8019:    }
1.29      www      8020: 
1.52      www      8021: #
1.103     harris41 8022: # Gathered now: all privileges that could apply, and condition number
1.52      www      8023: # 
                   8024: #
                   8025: # Full or no access?
                   8026: #
1.29      www      8027: 
1.52      www      8028:     if ($thisallowed=~/F/) {
                   8029: 	return 'F';
                   8030:     }
1.29      www      8031: 
1.52      www      8032:     unless ($thisallowed) {
                   8033:         return '';
                   8034:     }
1.29      www      8035: 
1.52      www      8036: # Restrictions exist, deal with them
                   8037: #
                   8038: #   C:according to course preferences
                   8039: #   R:according to resource settings
                   8040: #   L:unless locked
                   8041: #   X:according to user session state
                   8042: #
                   8043: 
                   8044: # Possibly locked functionality, check all courses
1.54      www      8045: # Locks might take effect only after 10 minutes cache expiration for other
                   8046: # courses, and 2 minutes for current course
1.52      www      8047: 
                   8048:     my $envkey;
                   8049:     if ($thisallowed=~/L/) {
1.1000    raeburn  8050:         foreach $envkey (keys(%env)) {
1.54      www      8051:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8052:                my $courseid=$2;
                   8053:                my $roleid=$1.'.'.$2;
1.92      www      8054:                $courseid=~s/^\///;
1.54      www      8055:                my $expiretime=600;
1.620     albertel 8056:                if ($env{'request.role'} eq $roleid) {
1.54      www      8057: 		  $expiretime=120;
                   8058:                }
                   8059: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8060:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8061:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8062: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8063:                }
1.620     albertel 8064:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8065:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8066: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8067:                        &log($env{'user.domain'},$env{'user.name'},
                   8068:                             $env{'user.home'},
1.57      www      8069:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8070:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8071:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8072: 		       return '';
                   8073:                    }
                   8074:                }
1.620     albertel 8075:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8076:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8077: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8078:                        &log($env{'user.domain'},$env{'user.name'},
                   8079:                             $env{'user.home'},
1.57      www      8080:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8081:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8082:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8083: 		       return '';
                   8084:                    }
                   8085:                }
                   8086: 	   }
1.29      www      8087:        }
1.52      www      8088:     }
                   8089:    
                   8090: #
                   8091: # Rest of the restrictions depend on selected course
                   8092: #
                   8093: 
1.620     albertel 8094:     unless ($env{'request.course.id'}) {
1.766     albertel 8095: 	if ($thisallowed eq 'A') {
                   8096: 	    return 'A';
1.814     raeburn  8097:         } elsif ($thisallowed eq 'B') {
                   8098:             return 'B';
1.766     albertel 8099: 	} else {
                   8100: 	    return '1';
                   8101: 	}
1.52      www      8102:     }
1.29      www      8103: 
1.52      www      8104: #
                   8105: # Now user is definitely in a course
                   8106: #
1.53      www      8107: 
                   8108: 
                   8109: # Course preferences
                   8110: 
                   8111:    if ($thisallowed=~/C/) {
1.620     albertel 8112:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8113:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8114:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8115: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8116: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8117: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8118: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8119: 			$env{'request.course.id'});
                   8120: 	   }
1.237     www      8121:            return '';
                   8122:        }
                   8123: 
1.620     albertel 8124:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8125: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8126: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8127: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8128: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8129: 			$env{'request.course.id'});
                   8130: 	   }
1.54      www      8131:            return '';
                   8132:        }
1.53      www      8133:    }
                   8134: 
                   8135: # Resource preferences
                   8136: 
                   8137:    if ($thisallowed=~/R/) {
1.620     albertel 8138:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8139:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8140: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8141: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8142: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8143: 	   }
                   8144: 	   return '';
1.54      www      8145:        }
1.53      www      8146:    }
1.30      www      8147: 
1.246     www      8148: # Restricted by state or randomout?
1.30      www      8149: 
1.52      www      8150:    if ($thisallowed=~/X/) {
1.620     albertel 8151:       if ($env{'acc.randomout'}) {
1.579     albertel 8152: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8153:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8154:             return ''; 
                   8155:          }
1.247     www      8156:       }
                   8157:       if (&condval($statecond)) {
1.52      www      8158: 	 return '2';
                   8159:       } else {
                   8160:          return '';
                   8161:       }
                   8162:    }
1.30      www      8163: 
1.766     albertel 8164:     if ($thisallowed eq 'A') {
                   8165: 	return 'A';
1.814     raeburn  8166:     } elsif ($thisallowed eq 'B') {
                   8167:         return 'B';
1.766     albertel 8168:     }
1.52      www      8169:    return 'F';
1.232     www      8170: }
1.1162    raeburn  8171: 
1.1172.2.13  raeburn  8172: # ------------------------------------------- Check construction space access
                   8173: 
                   8174: sub constructaccess {
                   8175:     my ($url,$setpriv)=@_;
                   8176: 
                   8177: # We do not allow editing of previous versions of files
                   8178:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8179: 
                   8180: # Get username and domain from URL
                   8181:     my ($ownername,$ownerdomain,$ownerhome);
                   8182: 
                   8183:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8184:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8185: 
                   8186: # The URL does not really point to any authorspace, forget it
                   8187:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8188: 
                   8189: # Now we need to see if the user has access to the authorspace of
                   8190: # $ownername at $ownerdomain
                   8191: 
                   8192:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8193: # Real author for this?
                   8194:        $ownerhome = $env{'user.home'};
                   8195:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8196:           return ($ownername,$ownerdomain,$ownerhome);
                   8197:        }
                   8198:     } else {
                   8199: # Co-author for this?
                   8200:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8201:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8202:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8203:             return ($ownername,$ownerdomain,$ownerhome);
                   8204:         }
                   8205:     }
                   8206: 
                   8207: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8208: # we might as well leave
                   8209:    unless ($setpriv) { return ''; }
                   8210: 
                   8211: # Backdoor access?
                   8212:     my $allowed=&allowed('eco',$ownerdomain);
                   8213: # Nope
                   8214:     unless ($allowed) { return ''; }
                   8215: # Looks like we may have access, but could be locked by the owner of the construction space
                   8216:     if ($allowed eq 'U') {
                   8217:         my %blocked=&get('environment',['domcoord.author'],
                   8218:                          $ownerdomain,$ownername);
                   8219: # Is blocked by owner
                   8220:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8221:     }
                   8222:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8223: # Grant temporary access
                   8224:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8225:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8226:         if (!$update) { $update = $then; }
                   8227:         my $refresh=$env{'user.refresh.time'};
                   8228:         if (!$refresh) { $refresh = $update; }
                   8229:         my $now = time;
                   8230:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8231:                            $now,'ca','constructaccess');
                   8232:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8233:         return($ownername,$ownerdomain,$ownerhome);
                   8234:     }
                   8235: # No business here
                   8236:     return '';
                   8237: }
                   8238: 
1.1172.2.66  raeburn  8239: # ----------------------------------------------------------- Content Blocking
                   8240: 
                   8241: {
                   8242: # Caches for faster Course Contents display where content blocking
                   8243: # is in operation (i.e., interval param set) for timed quiz.
                   8244: #
                   8245: # User for whom data are being temporarily cached.
                   8246: my $cacheduser='';
                   8247: # Cached blockers for this user (a hash of blocking items).
                   8248: my %cachedblockers=();
                   8249: # When the data were last cached.
                   8250: my $cachedlast='';
                   8251: 
                   8252: sub load_all_blockers {
                   8253:     my ($uname,$udom,$blocks)=@_;
                   8254:     if (($uname ne '') && ($udom ne '')) {
                   8255:         if (($cacheduser eq $uname.':'.$udom) &&
                   8256:             (abs($cachedlast-time)<5)) {
                   8257:             return;
                   8258:         }
                   8259:     }
                   8260:     $cachedlast=time;
                   8261:     $cacheduser=$uname.':'.$udom;
                   8262:     %cachedblockers = &get_commblock_resources($blocks);
                   8263: }
                   8264: 
1.1162    raeburn  8265: sub get_comm_blocks {
                   8266:     my ($cdom,$cnum) = @_;
                   8267:     if ($cdom eq '' || $cnum eq '') {
                   8268:         return unless ($env{'request.course.id'});
                   8269:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8270:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8271:     }
                   8272:     my %commblocks;
                   8273:     my $hashid=$cdom.'_'.$cnum;
                   8274:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8275:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8276:         %commblocks = %{$blocksref};
                   8277:     } else {
                   8278:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8279:         my $cachetime = 600;
                   8280:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8281:     }
                   8282:     return %commblocks;
                   8283: }
                   8284: 
1.1172.2.66  raeburn  8285: sub get_commblock_resources {
                   8286:     my ($blocks) = @_;
                   8287:     my %blockers = ();
                   8288:     return %blockers unless ($env{'request.course.id'});
                   8289:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8290:     my %commblocks;
                   8291:     if (ref($blocks) eq 'HASH') {
                   8292:         %commblocks = %{$blocks};
                   8293:     } else {
                   8294:         %commblocks = &get_comm_blocks();
                   8295:     }
1.1172.2.66  raeburn  8296:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8297:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8298:     return %blockers unless (ref($navmap));
                   8299:     my $now = time;
1.1162    raeburn  8300:     foreach my $block (keys(%commblocks)) {
                   8301:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8302:             my ($start,$end) = ($1,$2);
                   8303:             if ($start <= $now && $end >= $now) {
                   8304:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8305:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8306:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8307:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8308:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8309:                             }
                   8310:                         }
                   8311:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8312:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8313:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8314:                             }
                   8315:                         }
                   8316:                     }
                   8317:                 }
                   8318:             }
                   8319:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8320:             my $item = $1;
1.1163    raeburn  8321:             my @to_test;
1.1162    raeburn  8322:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8323:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8324:                     my @interval;
                   8325:                     my $type = 'map';
                   8326:                     if ($item eq 'course') {
                   8327:                         $type = 'course';
                   8328:                         @interval=&EXT("resource.0.interval");
                   8329:                     } else {
                   8330:                         if ($item =~ /___\d+___/) {
                   8331:                             $type = 'resource';
                   8332:                             @interval=&EXT("resource.0.interval",$item);
                   8333:                             if (ref($navmap)) {
                   8334:                                 my $res = $navmap->getBySymb($item);
                   8335:                                 push(@to_test,$res);
                   8336:                             }
1.1162    raeburn  8337:                         } else {
1.1172.2.66  raeburn  8338:                             my $mapsymb = &symbread($item,1);
                   8339:                             if ($mapsymb) {
                   8340:                                 if (ref($navmap)) {
                   8341:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8342:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8343:                                     foreach my $res (@to_test) {
                   8344:                                         my $symb = $res->symb();
                   8345:                                         next if ($symb eq $mapsymb);
                   8346:                                         if ($symb ne '') {
                   8347:                                             @interval=&EXT("resource.0.interval",$symb);
                   8348:                                             if ($interval[1] eq 'map') {
                   8349:                                                 last;
1.1162    raeburn  8350:                                             }
                   8351:                                         }
                   8352:                                     }
                   8353:                                 }
                   8354:                             }
                   8355:                         }
1.1172.2.66  raeburn  8356:                     }
                   8357:                     if ($interval[0] =~ /^\d+$/) {
                   8358:                         my $first_access;
                   8359:                         if ($type eq 'resource') {
                   8360:                             $first_access=&get_first_access($interval[1],$item);
                   8361:                         } elsif ($type eq 'map') {
                   8362:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8363:                         } else {
                   8364:                             $first_access=&get_first_access($interval[1]);
                   8365:                         }
                   8366:                         if ($first_access) {
                   8367:                             my $timesup = $first_access+$interval[0];
                   8368:                             if ($timesup > $now) {
                   8369:                                 my $activeblock;
                   8370:                                 foreach my $res (@to_test) {
                   8371:                                     if ($res->answerable()) {
                   8372:                                         $activeblock = 1;
                   8373:                                         last;
                   8374:                                     }
                   8375:                                 }
                   8376:                                 if ($activeblock) {
                   8377:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8378:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8379:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8380:                                          }
                   8381:                                     }
                   8382:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8383:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8384:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8385:                                         }
1.1162    raeburn  8386:                                     }
                   8387:                                 }
                   8388:                             }
                   8389:                         }
                   8390:                     }
                   8391:                 }
                   8392:             }
                   8393:         }
                   8394:     }
1.1172.2.66  raeburn  8395:     return %blockers;
1.1162    raeburn  8396: }
                   8397: 
1.1172.2.66  raeburn  8398: sub has_comm_blocking {
                   8399:     my ($priv,$symb,$uri,$blocks) = @_;
                   8400:     my @blockers;
                   8401:     return unless ($env{'request.course.id'});
                   8402:     return unless ($priv eq 'bre');
                   8403:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8404:     return if ($env{'request.state'} eq 'construct');
                   8405:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8406:     return unless (keys(%cachedblockers) > 0);
                   8407:     my (%possibles,@symbs);
                   8408:     if (!$symb) {
                   8409:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8410:     }
1.1172.2.66  raeburn  8411:     if ($symb) {
                   8412:         @symbs = ($symb);
                   8413:     } elsif (keys(%possibles)) {
                   8414:         @symbs = keys(%possibles);
                   8415:     }
                   8416:     my $noblock;
                   8417:     foreach my $symb (@symbs) {
                   8418:         last if ($noblock);
                   8419:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8420:         foreach my $block (keys(%cachedblockers)) {
                   8421:             if ($block =~ /^firstaccess____(.+)$/) {
                   8422:                 my $item = $1;
                   8423:                 if (($item eq $map) || ($item eq $symb)) {
                   8424:                     $noblock = 1;
                   8425:                     last;
                   8426:                 }
1.1162    raeburn  8427:             }
1.1172.2.66  raeburn  8428:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8429:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8430:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8431:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8432:                             push(@blockers,$block);
                   8433:                         }
                   8434:                     }
                   8435:                 }
                   8436:             }
                   8437:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8438:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8439:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8440:                         push(@blockers,$block);
                   8441:                     }
                   8442:                 }
1.1162    raeburn  8443:             }
                   8444:         }
                   8445:     }
1.1172.2.66  raeburn  8446:     return if ($noblock);
                   8447:     return @blockers;
                   8448: }
1.1162    raeburn  8449: }
                   8450: 
1.1172.2.66  raeburn  8451: # -------------------------------- Deversion and split uri into path an filename
                   8452: 
1.1133    foxr     8453: #
1.1172.2.66  raeburn  8454: #   Removes the version from a URI and
1.1133    foxr     8455: #   splits it in to its filename and path to the filename.
                   8456: #   Seems like File::Basename could have done this more clearly.
                   8457: #   Parameters:
                   8458: #      $uri   - input URI
                   8459: #   Returns:
                   8460: #     Two element list consisting of 
                   8461: #     $pathname  - the URI up to and excluding the trailing /
                   8462: #     $filename  - The part of the URI following the last /
                   8463: #  NOTE:
                   8464: #    Another realization of this is simply:
                   8465: #    use File::Basename;
                   8466: #    ...
                   8467: #    $uri = shift;
                   8468: #    $filename = basename($uri);
                   8469: #    $path     = dirname($uri);
                   8470: #    return ($filename, $path);
                   8471: #
                   8472: #     The implementation below is probably faster however.
                   8473: #
1.710     albertel 8474: sub split_uri_for_cond {
                   8475:     my $uri=&deversion(&declutter(shift));
                   8476:     my @uriparts=split(/\//,$uri);
                   8477:     my $filename=pop(@uriparts);
                   8478:     my $pathname=join('/',@uriparts);
                   8479:     return ($pathname,$filename);
                   8480: }
1.232     www      8481: # --------------------------------------------------- Is a resource on the map?
                   8482: 
                   8483: sub is_on_map {
1.710     albertel 8484:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8485:     #Trying to find the conditional for the file
1.620     albertel 8486:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8487: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8488:     if ($match) {
1.289     bowersj2 8489: 	return (1,$1);
                   8490:     } else {
1.434     www      8491: 	return (0,0);
1.289     bowersj2 8492:     }
1.12      www      8493: }
                   8494: 
1.427     www      8495: # --------------------------------------------------------- Get symb from alias
                   8496: 
                   8497: sub get_symb_from_alias {
                   8498:     my $symb=shift;
                   8499:     my ($map,$resid,$url)=&decode_symb($symb);
                   8500: # Already is a symb
                   8501:     if ($url) { return $symb; }
                   8502: # Must be an alias
                   8503:     my $aliassymb='';
                   8504:     my %bighash;
1.620     albertel 8505:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8506:                             &GDBM_READER(),0640)) {
                   8507:         my $rid=$bighash{'mapalias_'.$symb};
                   8508: 	if ($rid) {
                   8509: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8510: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8511: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8512: 	}
                   8513:         untie %bighash;
                   8514:     }
                   8515:     return $aliassymb;
                   8516: }
                   8517: 
1.12      www      8518: # ----------------------------------------------------------------- Define Role
                   8519: 
                   8520: sub definerole {
                   8521:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8522:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8523:     foreach my $role (split(':',$sysrole)) {
                   8524: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8525:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8526:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8527: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8528:                return "refused:s:$crole&$cqual"; 
                   8529:             }
                   8530:         }
1.191     harris41 8531:     }
1.800     albertel 8532:     foreach my $role (split(':',$domrole)) {
                   8533: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8534:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8535:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8536: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8537:                return "refused:d:$crole&$cqual"; 
                   8538:             }
                   8539:         }
1.191     harris41 8540:     }
1.800     albertel 8541:     foreach my $role (split(':',$courole)) {
                   8542: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8543:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8544:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8545: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8546:                return "refused:c:$crole&$cqual"; 
                   8547:             }
                   8548:         }
1.191     harris41 8549:     }
1.1172.2.84  raeburn  8550:     my $uhome;
                   8551:     if (($uname ne '') && ($udom ne '')) {
                   8552:         $uhome = &homeserver($uname,$udom);
                   8553:         return $uhome if ($uhome eq 'no_host');
                   8554:     } else {
                   8555:         $uname = $env{'user.name'};
                   8556:         $udom = $env{'user.domain'};
                   8557:         $uhome = $env{'user.home'};
                   8558:     }
1.620     albertel 8559:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8560:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8561:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8562:     return reply($command,$uhome);
1.12      www      8563:   } else {
                   8564:     return 'refused';
                   8565:   }
1.105     harris41 8566: }
                   8567: 
                   8568: # ---------------- Make a metadata query against the network of library servers
                   8569: 
                   8570: sub metadata_query {
1.1172.2.33  raeburn  8571:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8572:     my %rhash;
1.845     albertel 8573:     my %libserv = &all_library();
1.244     matthew  8574:     my @server_list = (defined($server_array) ? @$server_array
                   8575:                                               : keys(%libserv) );
                   8576:     for my $server (@server_list) {
1.1172.2.33  raeburn  8577:         my $domains = '';
                   8578:         if (ref($domains_hash) eq 'HASH') {
                   8579:             $domains = $domains_hash->{$server};    
                   8580:         }
1.118     harris41 8581: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8582: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8583: 	    $rhash{$server}=$reply;
                   8584: 	}
                   8585: 	else {
                   8586: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8587: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8588: 			     $server);
                   8589: 	    $rhash{$server}=$reply;
                   8590: 	}
1.112     harris41 8591:     }
1.118     harris41 8592:     return \%rhash;
1.240     www      8593: }
                   8594: 
                   8595: # ----------------------------------------- Send log queries and wait for reply
                   8596: 
                   8597: sub log_query {
                   8598:     my ($uname,$udom,$query,%filters)=@_;
                   8599:     my $uhome=&homeserver($uname,$udom);
                   8600:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8601:     my $uhost=&hostname($uhome);
1.800     albertel 8602:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8603:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8604:                        $uhome);
1.479     albertel 8605:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8606:     return get_query_reply($queryid);
                   8607: }
                   8608: 
1.818     raeburn  8609: # -------------------------- Update MySQL table for portfolio file
                   8610: 
                   8611: sub update_portfolio_table {
1.821     raeburn  8612:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8613:     if ($group ne '') {
                   8614:         $file_name =~s /^\Q$group\E//;
                   8615:     }
1.818     raeburn  8616:     my $homeserver = &homeserver($uname,$udom);
                   8617:     my $queryid=
1.821     raeburn  8618:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8619:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8620:     my $reply = &get_query_reply($queryid);
                   8621:     return $reply;
                   8622: }
                   8623: 
1.899     raeburn  8624: # -------------------------- Update MySQL allusers table
                   8625: 
                   8626: sub update_allusers_table {
                   8627:     my ($uname,$udom,$names) = @_;
                   8628:     my $homeserver = &homeserver($uname,$udom);
                   8629:     my $queryid=
                   8630:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8631:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8632:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8633:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8634:                'generation='.&escape($names->{'generation'}).'%%'.
                   8635:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8636:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8637:     return;
1.899     raeburn  8638: }
                   8639: 
1.508     raeburn  8640: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8641: 
                   8642: sub fetch_enrollment_query {
1.511     raeburn  8643:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8644:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8645:     my $maxtries = 1;
1.508     raeburn  8646:     if ($context eq 'automated') {
                   8647:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8648:         $sleep = 2;
                   8649:         $loopmax = 100;
1.547     raeburn  8650:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8651:     } else {
                   8652:         $homeserver = &homeserver($cnum,$dom);
                   8653:     }
1.838     albertel 8654:     my $host=&hostname($homeserver);
1.506     raeburn  8655:     my $cmd = '';
1.1000    raeburn  8656:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8657:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8658:     }
                   8659:     $cmd =~ s/%%$//;
                   8660:     $cmd = &escape($cmd);
                   8661:     my $query = 'fetchenrollment';
1.620     albertel 8662:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8663:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8664:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8665:         return 'error: '.$queryid;
                   8666:     }
1.1172.2.93  raeburn  8667:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8668:     my $tries = 1;
                   8669:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8670:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8671:         $tries ++;
                   8672:     }
1.526     raeburn  8673:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8674:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8675:     } else {
1.901     albertel 8676:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8677:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8678:             foreach my $line (@responses) {
                   8679:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8680:                 $$replyref{$key} = $value;
                   8681:             }
                   8682:         } else {
1.1117    foxr     8683:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8684:             foreach my $line (@responses) {
                   8685:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8686:                 $$replyref{$key} = $value;
                   8687:                 if ($value > 0) {
1.800     albertel 8688:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8689:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8690:                         my $destname = $pathname.'/'.$filename;
                   8691:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8692:                         if ($xml_classlist =~ /^error/) {
                   8693:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8694:                         } else {
1.1172.2.96  raeburn  8695:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8696:                                 print FILE &unescape($xml_classlist);
                   8697:                                 close(FILE);
1.526     raeburn  8698:                             } else {
                   8699:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8700:                             }
                   8701:                         }
                   8702:                     }
                   8703:                 }
                   8704:             }
                   8705:         }
                   8706:         return 'ok';
                   8707:     }
                   8708:     return 'error';
                   8709: }
                   8710: 
1.242     www      8711: sub get_query_reply {
1.1172.2.79  raeburn  8712:     my ($queryid,$sleep,$loopmax) = @_;
                   8713:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8714:         $sleep = 0.2;
                   8715:     }
                   8716:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8717:         $loopmax = 100;
                   8718:     }
1.1117    foxr     8719:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8720:     my $reply='';
1.1172.2.79  raeburn  8721:     for (1..$loopmax) {
                   8722: 	sleep($sleep);
1.240     www      8723:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8724: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8725: 		$reply = join('',<$fh>);
                   8726: 		close($fh);
1.240     www      8727: 	   } else { return 'error: reply_file_error'; }
1.242     www      8728:            return &unescape($reply);
                   8729: 	}
1.240     www      8730:     }
1.242     www      8731:     return 'timeout:'.$queryid;
1.240     www      8732: }
                   8733: 
                   8734: sub courselog_query {
1.241     www      8735: #
                   8736: # possible filters:
                   8737: # url: url or symb
                   8738: # username
                   8739: # domain
                   8740: # action: view, submit, grade
                   8741: # start: timestamp
                   8742: # end: timestamp
                   8743: #
1.240     www      8744:     my (%filters)=@_;
1.620     albertel 8745:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8746:     if ($filters{'url'}) {
                   8747: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8748:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8749:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8750:     }
1.620     albertel 8751:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8752:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8753:     return &log_query($cname,$cdom,'courselog',%filters);
                   8754: }
                   8755: 
                   8756: sub userlog_query {
1.858     raeburn  8757: #
                   8758: # possible filters:
                   8759: # action: log check role
                   8760: # start: timestamp
                   8761: # end: timestamp
                   8762: #
1.240     www      8763:     my ($uname,$udom,%filters)=@_;
                   8764:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8765: }
                   8766: 
1.506     raeburn  8767: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8768: 
                   8769: sub auto_run {
1.508     raeburn  8770:     my ($cnum,$cdom) = @_;
1.876     raeburn  8771:     my $response = 0;
                   8772:     my $settings;
                   8773:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8774:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8775:         $settings = $domconfig{'autoenroll'};
                   8776:         if ($settings->{'run'} eq '1') {
                   8777:             $response = 1;
                   8778:         }
                   8779:     } else {
1.934     raeburn  8780:         my $homeserver;
                   8781:         if (&is_course($cdom,$cnum)) {
                   8782:             $homeserver = &homeserver($cnum,$cdom);
                   8783:         } else {
                   8784:             $homeserver = &domain($cdom,'primary');
                   8785:         }
                   8786:         if ($homeserver ne 'no_host') {
                   8787:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8788:         }
1.876     raeburn  8789:     }
1.506     raeburn  8790:     return $response;
                   8791: }
1.776     albertel 8792: 
1.506     raeburn  8793: sub auto_get_sections {
1.508     raeburn  8794:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8795:     my $homeserver;
                   8796:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8797:         $homeserver = &homeserver($cnum,$cdom);
                   8798:     }
                   8799:     if (!defined($homeserver)) { 
                   8800:         if ($cdom =~ /^$match_domain$/) {
                   8801:             $homeserver = &domain($cdom,'primary');
                   8802:         }
                   8803:     }
                   8804:     my @secs;
                   8805:     if (defined($homeserver)) {
                   8806:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8807:         unless ($response eq 'refused') {
                   8808:             @secs = split(/:/,$response);
                   8809:         }
1.506     raeburn  8810:     }
                   8811:     return @secs;
                   8812: }
1.776     albertel 8813: 
1.506     raeburn  8814: sub auto_new_course {
1.1099    raeburn  8815:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8816:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8817:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8818:     return $response;
                   8819: }
1.776     albertel 8820: 
1.506     raeburn  8821: sub auto_validate_courseID {
1.508     raeburn  8822:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8823:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8824:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8825:     return $response;
                   8826: }
1.776     albertel 8827: 
1.1007    raeburn  8828: sub auto_validate_instcode {
1.1020    raeburn  8829:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8830:     my ($homeserver,$response);
                   8831:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8832:         $homeserver = &homeserver($cnum,$cdom);
                   8833:     }
                   8834:     if (!defined($homeserver)) {
                   8835:         if ($cdom =~ /^$match_domain$/) {
                   8836:             $homeserver = &domain($cdom,'primary');
                   8837:         }
                   8838:     }
1.1065    raeburn  8839:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8840:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8841:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8842:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8843: }
                   8844: 
1.506     raeburn  8845: sub auto_create_password {
1.873     raeburn  8846:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8847:     my ($homeserver,$response);
1.506     raeburn  8848:     my $create_passwd = 0;
                   8849:     my $authchk = '';
1.873     raeburn  8850:     if ($udom =~ /^$match_domain$/) {
                   8851:         $homeserver = &domain($udom,'primary');
                   8852:     }
                   8853:     if ($homeserver eq '') {
                   8854:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8855:             $homeserver = &homeserver($cnum,$cdom);
                   8856:         }
                   8857:     }
                   8858:     if ($homeserver eq '') {
                   8859:         $authchk = 'nodomain';
1.506     raeburn  8860:     } else {
1.873     raeburn  8861:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8862:         if ($response eq 'refused') {
                   8863:             $authchk = 'refused';
                   8864:         } else {
1.901     albertel 8865:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8866:         }
1.506     raeburn  8867:     }
                   8868:     return ($authparam,$create_passwd,$authchk);
                   8869: }
                   8870: 
1.706     raeburn  8871: sub auto_photo_permission {
                   8872:     my ($cnum,$cdom,$students) = @_;
                   8873:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8874:     my ($outcome,$perm_reqd,$conditions) = 
                   8875: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8876:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8877: 	return (undef,undef);
                   8878:     }
1.706     raeburn  8879:     return ($outcome,$perm_reqd,$conditions);
                   8880: }
                   8881: 
                   8882: sub auto_checkphotos {
                   8883:     my ($uname,$udom,$pid) = @_;
                   8884:     my $homeserver = &homeserver($uname,$udom);
                   8885:     my ($result,$resulttype);
                   8886:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8887: 				   &escape($uname).':'.&escape($pid),
                   8888: 				   $homeserver));
1.709     albertel 8889:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8890: 	return (undef,undef);
                   8891:     }
1.706     raeburn  8892:     if ($outcome) {
                   8893:         ($result,$resulttype) = split(/:/,$outcome);
                   8894:     } 
                   8895:     return ($result,$resulttype);
                   8896: }
                   8897: 
                   8898: sub auto_photochoice {
                   8899:     my ($cnum,$cdom) = @_;
                   8900:     my $homeserver = &homeserver($cnum,$cdom);
                   8901:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8902: 						       &escape($cdom),
                   8903: 						       $homeserver)));
1.709     albertel 8904:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8905: 	return (undef,undef);
                   8906:     }
1.706     raeburn  8907:     return ($update,$comment);
                   8908: }
                   8909: 
                   8910: sub auto_photoupdate {
                   8911:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8912:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8913:     my $host=&hostname($homeserver);
1.706     raeburn  8914:     my $cmd = '';
                   8915:     my $maxtries = 1;
1.800     albertel 8916:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8917:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8918:     }
                   8919:     $cmd =~ s/%%$//;
                   8920:     $cmd = &escape($cmd);
                   8921:     my $query = 'institutionalphotos';
                   8922:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8923:     unless ($queryid=~/^\Q$host\E\_/) {
                   8924:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8925:         return 'error: '.$queryid;
                   8926:     }
                   8927:     my $reply = &get_query_reply($queryid);
                   8928:     my $tries = 1;
                   8929:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8930:         $reply = &get_query_reply($queryid);
                   8931:         $tries ++;
                   8932:     }
                   8933:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8934:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8935:     } else {
                   8936:         my @responses = split(/:/,$reply);
                   8937:         my $outcome = shift(@responses); 
                   8938:         foreach my $item (@responses) {
                   8939:             my ($key,$value) = split(/=/,$item);
                   8940:             $$photo{$key} = $value;
                   8941:         }
                   8942:         return $outcome;
                   8943:     }
                   8944:     return 'error';
                   8945: }
                   8946: 
1.521     raeburn  8947: sub auto_instcode_format {
1.793     albertel 8948:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8949: 	$cat_order) = @_;
1.521     raeburn  8950:     my $courses = '';
1.772     raeburn  8951:     my @homeservers;
1.521     raeburn  8952:     if ($caller eq 'global') {
1.841     albertel 8953: 	my %servers = &get_servers($codedom,'library');
                   8954: 	foreach my $tryserver (keys(%servers)) {
                   8955: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8956: 		push(@homeservers,$tryserver);
                   8957: 	    }
1.584     raeburn  8958:         }
1.1022    raeburn  8959:     } elsif ($caller eq 'requests') {
                   8960:         if ($codedom =~ /^$match_domain$/) {
                   8961:             my $chome = &domain($codedom,'primary');
                   8962:             unless ($chome eq 'no_host') {
                   8963:                 push(@homeservers,$chome);
                   8964:             }
                   8965:         }
1.521     raeburn  8966:     } else {
1.772     raeburn  8967:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8968:     }
1.793     albertel 8969:     foreach my $code (keys(%{$instcodes})) {
                   8970:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8971:     }
                   8972:     chop($courses);
1.772     raeburn  8973:     my $ok_response = 0;
                   8974:     my $response;
                   8975:     while (@homeservers > 0 && $ok_response == 0) {
                   8976:         my $server = shift(@homeservers); 
                   8977:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8978:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8979:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8980: 		split(/:/,$response);
1.772     raeburn  8981:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8982:             push(@{$codetitles},&str2array($codetitles_str));
                   8983:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8984:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8985:             $ok_response = 1;
                   8986:         }
                   8987:     }
                   8988:     if ($ok_response) {
1.521     raeburn  8989:         return 'ok';
1.772     raeburn  8990:     } else {
                   8991:         return $response;
1.521     raeburn  8992:     }
                   8993: }
                   8994: 
1.792     raeburn  8995: sub auto_instcode_defaults {
                   8996:     my ($domain,$returnhash,$code_order) = @_;
                   8997:     my @homeservers;
1.841     albertel 8998: 
                   8999:     my %servers = &get_servers($domain,'library');
                   9000:     foreach my $tryserver (keys(%servers)) {
                   9001: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9002: 	    push(@homeservers,$tryserver);
                   9003: 	}
1.792     raeburn  9004:     }
1.841     albertel 9005: 
1.792     raeburn  9006:     my $response;
1.841     albertel 9007:     foreach my $server (@homeservers) {
1.792     raeburn  9008:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9009:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9010: 	
                   9011: 	foreach my $pair (split(/\&/,$response)) {
                   9012: 	    my ($name,$value)=split(/\=/,$pair);
                   9013: 	    if ($name eq 'code_order') {
                   9014: 		@{$code_order} = split(/\&/,&unescape($value));
                   9015: 	    } else {
                   9016: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9017: 	    }
                   9018: 	}
                   9019: 	return 'ok';
1.792     raeburn  9020:     }
1.841     albertel 9021: 
                   9022:     return $response;
1.1003    raeburn  9023: }
                   9024: 
                   9025: sub auto_possible_instcodes {
1.1007    raeburn  9026:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9027:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9028:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9029:         return;
                   9030:     }
1.1003    raeburn  9031:     my (@homeservers,$uhome);
                   9032:     if (defined(&domain($domain,'primary'))) {
                   9033:         $uhome=&domain($domain,'primary');
                   9034:         push(@homeservers,&domain($domain,'primary'));
                   9035:     } else {
                   9036:         my %servers = &get_servers($domain,'library');
                   9037:         foreach my $tryserver (keys(%servers)) {
                   9038:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9039:                 push(@homeservers,$tryserver);
                   9040:             }
                   9041:         }
                   9042:     }
                   9043:     my $response;
                   9044:     foreach my $server (@homeservers) {
                   9045:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9046:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9047:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9048:             split(':',$response);
                   9049:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9050:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9051:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9052:             my ($name,$value)=split('=',$item);
                   9053:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9054:         }
                   9055:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9056:             my ($name,$value)=split('=',$item);
                   9057:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9058:         }
                   9059:         return 'ok';
                   9060:     }
                   9061:     return $response;
                   9062: }
1.792     raeburn  9063: 
1.1010    raeburn  9064: sub auto_courserequest_checks {
                   9065:     my ($dom) = @_;
1.1020    raeburn  9066:     my ($homeserver,%validations);
                   9067:     if ($dom =~ /^$match_domain$/) {
                   9068:         $homeserver = &domain($dom,'primary');
                   9069:     }
                   9070:     unless ($homeserver eq 'no_host') {
                   9071:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9072:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9073:             my @items = split(/&/,$response);
                   9074:             foreach my $item (@items) {
                   9075:                 my ($key,$value) = split('=',$item);
                   9076:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9077:             }
                   9078:         }
                   9079:     }
1.1010    raeburn  9080:     return %validations; 
                   9081: }
                   9082: 
1.1020    raeburn  9083: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9084:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9085:     my ($homeserver,$response);
                   9086:     if ($dom =~ /^$match_domain$/) {
                   9087:         $homeserver = &domain($dom,'primary');
                   9088:     }
1.1172.2.43  raeburn  9089:     unless ($homeserver eq 'no_host') {
                   9090:         my $customdata;
                   9091:         if (ref($custominfo) eq 'HASH') {
                   9092:             $customdata = &freeze_escape($custominfo);
                   9093:         }
1.1020    raeburn  9094:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9095:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9096:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9097:                                     $customdata,$homeserver));
1.1020    raeburn  9098:     }
                   9099:     return $response;
                   9100: }
                   9101: 
1.777     albertel 9102: sub auto_validate_class_sec {
1.918     raeburn  9103:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9104:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9105:     my $ownerlist;
                   9106:     if (ref($owners) eq 'ARRAY') {
                   9107:         $ownerlist = join(',',@{$owners});
                   9108:     } else {
                   9109:         $ownerlist = $owners;
                   9110:     }
1.773     raeburn  9111:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9112:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9113:     return $response;
                   9114: }
                   9115: 
1.1172.2.94  raeburn  9116: sub auto_validate_instclasses {
                   9117:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9118:     my ($homeserver,%validations);
                   9119:     $homeserver = &homeserver($cnum,$cdom);
                   9120:     unless ($homeserver eq 'no_host') {
                   9121:         my $ownerlist;
                   9122:         if (ref($owners) eq 'ARRAY') {
                   9123:             $ownerlist = join(',',@{$owners});
                   9124:         } else {
                   9125:             $ownerlist = $owners;
                   9126:         }
                   9127:         if (ref($classesref) eq 'HASH') {
                   9128:             my $classes = &freeze_escape($classesref);
                   9129:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9130:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9131:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9132:                 my @items = split(/&/,$response);
                   9133:                 foreach my $item (@items) {
                   9134:                     my ($key,$value) = split('=',$item);
                   9135:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9136:                 }
                   9137:             }
                   9138:         }
                   9139:     }
                   9140:     return %validations;
                   9141: }
                   9142: 
1.1172.2.38  raeburn  9143: sub auto_crsreq_update {
                   9144:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9145:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9146:     my ($homeserver,%crsreqresponse);
                   9147:     if ($cdom =~ /^$match_domain$/) {
                   9148:         $homeserver = &domain($cdom,'primary');
                   9149:     }
                   9150:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9151:         my $info;
                   9152:         if (ref($inbound) eq 'HASH') {
                   9153:             $info = &freeze_escape($inbound);
                   9154:         }
                   9155:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9156:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9157:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9158:                             &escape($title).':'.&escape($code).':'.
                   9159:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9160:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9161:             my @items = split(/&/,$response);
                   9162:             foreach my $item (@items) {
                   9163:                 my ($key,$value) = split('=',$item);
                   9164:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9165:             }
                   9166:         }
                   9167:     }
                   9168:     return \%crsreqresponse;
                   9169: }
                   9170: 
1.1172.2.78  raeburn  9171: sub auto_export_grades {
                   9172:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9173:     my ($homeserver,%exportresponse);
                   9174:     if ($cdom =~ /^$match_domain$/) {
                   9175:         $homeserver = &domain($cdom,'primary');
                   9176:     }
                   9177:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9178:         my $info;
                   9179:         if (ref($inforef) eq 'HASH') {
                   9180:             $info = &freeze_escape($inforef);
                   9181:         }
                   9182:         if (ref($gradesref) eq 'HASH') {
                   9183:             my $grades = &freeze_escape($gradesref);
                   9184:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9185:                                 $info.':'.$grades,$homeserver);
                   9186:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9187:                 my @items = split(/&/,$response);
                   9188:                 foreach my $item (@items) {
                   9189:                     my ($key,$value) = split('=',$item);
                   9190:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9191:                 }
                   9192:             }
                   9193:         }
                   9194:     }
                   9195:     return \%exportresponse;
                   9196: }
                   9197: 
1.1172.2.68  raeburn  9198: sub check_instcode_cloning {
                   9199:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9200:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9201:         return;
                   9202:     }
                   9203:     my $canclone;
                   9204:     if (@{$code_order} > 0) {
                   9205:         my $instcoderegexp ='^';
                   9206:         my @clonecodes = split(/\&/,$cloner);
                   9207:         foreach my $item (@{$code_order}) {
                   9208:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9209:                 foreach my $pair (@clonecodes) {
                   9210:                     my ($key,$val) = split(/\=/,$pair,2);
                   9211:                     $val = &unescape($val);
                   9212:                     if ($key eq $item) {
                   9213:                         $instcoderegexp .= '('.$val.')';
                   9214:                         last;
                   9215:                     }
                   9216:                 }
                   9217:             } else {
                   9218:                 $instcoderegexp .= $codedefaults->{$item};
                   9219:             }
                   9220:         }
                   9221:         $instcoderegexp .= '$';
                   9222:         my (@from,@to);
                   9223:         eval {
                   9224:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9225:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9226:         };
                   9227:         if ((@from > 0) && (@to > 0)) {
                   9228:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9229:             if (!@diffs) {
                   9230:                 $canclone = 1;
                   9231:             }
                   9232:         }
                   9233:     }
                   9234:     return $canclone;
                   9235: }
                   9236: 
                   9237: sub default_instcode_cloning {
                   9238:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9239:     my (%codedefaults,@code_order,$canclone);
                   9240:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9241:         %codedefaults = %{$codedefaultsref};
                   9242:         @code_order = @{$codeorderref};
                   9243:     } elsif ($clonedom) {
                   9244:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9245:     }
                   9246:     if (($domdefclone) && (@code_order)) {
                   9247:         my @clonecodes = split(/\+/,$domdefclone);
                   9248:         my $instcoderegexp ='^';
                   9249:         foreach my $item (@code_order) {
                   9250:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9251:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9252:             } else {
                   9253:                 $instcoderegexp .= $codedefaults{$item};
                   9254:             }
                   9255:         }
                   9256:         $instcoderegexp .= '$';
                   9257:         my (@from,@to);
                   9258:         eval {
                   9259:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9260:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9261:         };
                   9262:         if ((@from > 0) && (@to > 0)) {
                   9263:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9264:             if (!@diffs) {
                   9265:                 $canclone = 1;
                   9266:             }
                   9267:         }
                   9268:     }
                   9269:     return $canclone;
                   9270: }
                   9271: 
1.679     raeburn  9272: # ------------------------------------------------------- Course Group routines
                   9273: 
                   9274: sub get_coursegroups {
1.809     raeburn  9275:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9276:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9277: }
                   9278: 
1.679     raeburn  9279: sub modify_coursegroup {
                   9280:     my ($cdom,$cnum,$groupsettings) = @_;
                   9281:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9282: }
                   9283: 
1.809     raeburn  9284: sub toggle_coursegroup_status {
                   9285:     my ($cdom,$cnum,$group,$action) = @_;
                   9286:     my ($from_namespace,$to_namespace);
                   9287:     if ($action eq 'delete') {
                   9288:         $from_namespace = 'coursegroups';
                   9289:         $to_namespace = 'deleted_groups';
                   9290:     } else {
                   9291:         $from_namespace = 'deleted_groups';
                   9292:         $to_namespace = 'coursegroups';
                   9293:     }
                   9294:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9295:     if (my $tmp = &error(%curr_group)) {
                   9296:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9297:         return ('read error',$tmp);
                   9298:     } else {
                   9299:         my %savedsettings = %curr_group; 
1.809     raeburn  9300:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9301:         my $deloutcome;
                   9302:         if ($result eq 'ok') {
1.809     raeburn  9303:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9304:         } else {
                   9305:             return ('write error',$result);
                   9306:         }
                   9307:         if ($deloutcome eq 'ok') {
                   9308:             return 'ok';
                   9309:         } else {
                   9310:             return ('delete error',$deloutcome);
                   9311:         }
                   9312:     }
                   9313: }
                   9314: 
1.679     raeburn  9315: sub modify_group_roles {
1.957     raeburn  9316:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9317:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9318:     my $role = 'gr/'.&escape($userprivs);
                   9319:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9320:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9321:     if ($result eq 'ok') {
                   9322:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9323:     }
1.679     raeburn  9324:     return $result;
                   9325: }
                   9326: 
                   9327: sub modify_coursegroup_membership {
                   9328:     my ($cdom,$cnum,$membership) = @_;
                   9329:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9330:     return $result;
                   9331: }
                   9332: 
1.682     raeburn  9333: sub get_active_groups {
                   9334:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9335:     my $now = time;
                   9336:     my %groups = ();
                   9337:     foreach my $key (keys(%env)) {
1.811     albertel 9338:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9339:             my ($start,$end) = split(/\./,$env{$key});
                   9340:             if (($end!=0) && ($end<$now)) { next; }
                   9341:             if (($start!=0) && ($start>$now)) { next; }
                   9342:             if ($1 eq $cdom && $2 eq $cnum) {
                   9343:                 $groups{$3} = $env{$key} ;
                   9344:             }
                   9345:         }
                   9346:     }
                   9347:     return %groups;
                   9348: }
                   9349: 
1.683     raeburn  9350: sub get_group_membership {
                   9351:     my ($cdom,$cnum,$group) = @_;
                   9352:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9353: }
                   9354: 
                   9355: sub get_users_groups {
                   9356:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9357:     my @usersgroups;
1.683     raeburn  9358:     my $cachetime=1800;
                   9359: 
                   9360:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9361:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9362:     if (defined($cached)) {
1.734     albertel 9363:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9364:     } else {  
                   9365:         $grouplist = '';
1.816     raeburn  9366:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9367:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9368:         my $access_end = $env{'course.'.$courseid.
                   9369:                               '.default_enrollment_end_date'};
                   9370:         my $now = time;
                   9371:         foreach my $key (keys(%roleshash)) {
                   9372:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9373:                 my $group = $1;
                   9374:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9375:                     my $start = $2;
                   9376:                     my $end = $1;
                   9377:                     if ($start == -1) { next; } # deleted from group
                   9378:                     if (($start!=0) && ($start>$now)) { next; }
                   9379:                     if (($end!=0) && ($end<$now)) {
                   9380:                         if ($access_end && $access_end < $now) {
                   9381:                             if ($access_end - $end < 86400) {
                   9382:                                 push(@usersgroups,$group);
1.733     raeburn  9383:                             }
                   9384:                         }
1.817     raeburn  9385:                         next;
1.733     raeburn  9386:                     }
1.817     raeburn  9387:                     push(@usersgroups,$group);
1.683     raeburn  9388:                 }
                   9389:             }
                   9390:         }
1.817     raeburn  9391:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9392:         $grouplist = join(':',@usersgroups);
                   9393:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9394:     }
1.733     raeburn  9395:     return @usersgroups;
1.683     raeburn  9396: }
                   9397: 
                   9398: sub devalidate_getgroups_cache {
                   9399:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9400:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9401: 
1.683     raeburn  9402:     my $hashid="$udom:$uname:$courseid";
                   9403:     &devalidate_cache_new('getgroups',$hashid);
                   9404: }
                   9405: 
1.12      www      9406: # ------------------------------------------------------------------ Plain Text
                   9407: 
                   9408: sub plaintext {
1.988     raeburn  9409:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9410:     if ($short =~ m{^cr/}) {
1.758     albertel 9411: 	return (split('/',$short))[-1];
                   9412:     }
1.742     raeburn  9413:     if (!defined($cid)) {
                   9414:         $cid = $env{'request.course.id'};
                   9415:     }
                   9416:     my %rolenames = (
1.1008    raeburn  9417:                       Course    => 'std',
                   9418:                       Community => 'alt1',
1.742     raeburn  9419:                     );
1.1037    raeburn  9420:     if ($cid ne '') {
                   9421:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9422:             unless ($forcedefault) {
                   9423:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9424:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9425:                 return &Apache::lonlocal::mt($roletext);
                   9426:             }
                   9427:         }
                   9428:     }
                   9429:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9430:         (defined($rolenames{$type})) && 
                   9431:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9432:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9433:     } elsif ($cid ne '') {
                   9434:         my $crstype = $env{'course.'.$cid.'.type'};
                   9435:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9436:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9437:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9438:         }
1.742     raeburn  9439:     }
1.1037    raeburn  9440:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9441: }
                   9442: 
                   9443: # ----------------------------------------------------------------- Assign Role
                   9444: 
                   9445: sub assignrole {
1.957     raeburn  9446:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9447:         $context)=@_;
1.21      www      9448:     my $mrole;
                   9449:     if ($role =~ /^cr\//) {
1.393     www      9450:         my $cwosec=$url;
1.811     albertel 9451:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9452: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9453:            my $refused = 1;
                   9454:            if ($context eq 'requestcourses') {
                   9455:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9456:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9457:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9458:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9459:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9460:                            if ($crsenv{'internal.courseowner'} eq
                   9461:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9462:                                $refused = '';
                   9463:                            }
                   9464:                        }
                   9465:                    }
                   9466:                }
                   9467:            }
                   9468:            if ($refused) {
                   9469:                &logthis('Refused custom assignrole: '.
                   9470:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9471:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9472:                return 'refused';
                   9473:            }
1.104     www      9474:         }
1.21      www      9475:         $mrole='cr';
1.678     raeburn  9476:     } elsif ($role =~ /^gr\//) {
                   9477:         my $cwogrp=$url;
1.811     albertel 9478:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9479:         unless (&allowed('mdg',$cwogrp)) {
                   9480:             &logthis('Refused group assignrole: '.
                   9481:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9482:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9483:             return 'refused';
                   9484:         }
                   9485:         $mrole='gr';
1.21      www      9486:     } else {
1.82      www      9487:         my $cwosec=$url;
1.811     albertel 9488:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9489:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9490:             my $refused;
                   9491:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9492:                 if (!(&allowed('c'.$role,$url))) {
                   9493:                     $refused = 1;
                   9494:                 }
                   9495:             } else {
                   9496:                 $refused = 1;
                   9497:             }
1.947     raeburn  9498:             if ($refused) {
1.1045    raeburn  9499:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9500:                 if (!$selfenroll && $context eq 'course') {
                   9501:                     my %crsenv;
                   9502:                     if ($role eq 'cc' || $role eq 'co') {
                   9503:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9504:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9505:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9506:                                 if ($crsenv{'internal.courseowner'} eq 
                   9507:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9508:                                     $refused = '';
                   9509:                                 }
                   9510:                             }
                   9511:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9512:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9513:                                 if ($crsenv{'internal.courseowner'} eq 
                   9514:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9515:                                     $refused = '';
                   9516:                                 }
                   9517:                             }
                   9518:                         }
                   9519:                     }
                   9520:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9521:                     $refused = '';
1.1017    raeburn  9522:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9523:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9524:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9525:                         my $wrongcc;
                   9526:                         if ($cnum =~ /^$match_community$/) {
                   9527:                             $wrongcc = 1 if ($role eq 'cc');
                   9528:                         } else {
                   9529:                             $wrongcc = 1 if ($role eq 'co');
                   9530:                         }
                   9531:                         unless ($wrongcc) {
                   9532:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9533:                             if ($crsenv{'internal.courseowner'} eq 
                   9534:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9535:                                 $refused = '';
                   9536:                             }
1.1017    raeburn  9537:                         }
                   9538:                     }
1.1172.2.9  raeburn  9539:                 } elsif ($context eq 'requestauthor') {
                   9540:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9541:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9542:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9543:                             $refused = '';
                   9544:                         } else {
                   9545:                             my %domdefaults = &get_domain_defaults($udom);
                   9546:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9547:                                 my $checkbystatus;
                   9548:                                 if ($env{'user.adv'}) {
                   9549:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9550:                                     if ($disposition eq 'automatic') {
                   9551:                                         $refused = '';
                   9552:                                     } elsif ($disposition eq '') {
                   9553:                                         $checkbystatus = 1;
                   9554:                                     }
                   9555:                                 } else {
                   9556:                                     $checkbystatus = 1;
                   9557:                                 }
                   9558:                                 if ($checkbystatus) {
                   9559:                                     if ($env{'environment.inststatus'}) {
                   9560:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9561:                                         foreach my $type (@inststatuses) {
                   9562:                                             if (($type ne '') &&
                   9563:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9564:                                                 $refused = '';
                   9565:                                             }
                   9566:                                         }
                   9567:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9568:                                         $refused = '';
                   9569:                                     }
                   9570:                                 }
                   9571:                             }
                   9572:                         }
                   9573:                     }
1.1017    raeburn  9574:                 }
                   9575:                 if ($refused) {
1.947     raeburn  9576:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9577:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9578: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9579:                     return 'refused';
                   9580:                 }
1.932     raeburn  9581:             }
1.1131    raeburn  9582:         } elsif ($role eq 'au') {
                   9583:             if ($url ne '/'.$udom.'/') {
                   9584:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9585:                          ' to assign author role for '.$uname.':'.$udom.
                   9586:                          ' in domain: '.$url.' refused (wrong domain).');
                   9587:                 return 'refused';
                   9588:             }
1.104     www      9589:         }
1.21      www      9590:         $mrole=$role;
                   9591:     }
1.620     albertel 9592:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9593:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9594:     if ($end) { $command.='_'.$end; }
1.21      www      9595:     if ($start) {
                   9596: 	if ($end) { 
1.81      www      9597:            $command.='_'.$start; 
1.21      www      9598:         } else {
1.81      www      9599:            $command.='_0_'.$start;
1.21      www      9600:         }
                   9601:     }
1.739     raeburn  9602:     my $origstart = $start;
                   9603:     my $origend = $end;
1.957     raeburn  9604:     my $delflag;
1.357     www      9605: # actually delete
                   9606:     if ($deleteflag) {
1.373     www      9607: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9608: # modify command to delete the role
1.620     albertel 9609:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9610:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9611: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9612: # set start and finish to negative values for userrolelog
                   9613:            $start=-1;
                   9614:            $end=-1;
1.957     raeburn  9615:            $delflag = 1;
1.357     www      9616:         }
                   9617:     }
                   9618: # send command
1.349     www      9619:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9620: # log new user role if status is ok
1.349     www      9621:     if ($answer eq 'ok') {
1.663     raeburn  9622: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9623:         if (($role eq 'cc') || ($role eq 'in') ||
                   9624:             ($role eq 'ep') || ($role eq 'ad') ||
                   9625:             ($role eq 'ta') || ($role eq 'st') ||
                   9626:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9627:             ($role eq 'co')) {
1.1172.2.13  raeburn  9628: # for course roles, perform group memberships changes triggered by role change.
                   9629:             unless ($role =~ /^gr/) {
                   9630:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9631:                                                  $origstart,$selfenroll,$context);
                   9632:             }
1.1172.2.9  raeburn  9633:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9634:                            $selfenroll,$context);
                   9635:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9636:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9637:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9638:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9639:                            $context);
                   9640:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9641:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9642:                              $context);
                   9643:         }
1.1053    raeburn  9644:         if ($role eq 'cc') {
                   9645:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9646:         }
1.349     www      9647:     }
                   9648:     return $answer;
1.169     harris41 9649: }
                   9650: 
1.1053    raeburn  9651: sub autoupdate_coowners {
                   9652:     my ($url,$end,$start,$uname,$udom) = @_;
                   9653:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9654:     if (($cdom ne '') && ($cnum ne '')) {
                   9655:         my $now = time;
                   9656:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9657:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9658:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9659:             my $instcode = $coursehash{'internal.coursecode'};
                   9660:             if ($instcode ne '') {
1.1056    raeburn  9661:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9662:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9663:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9664:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9665:                         if ($result eq 'valid') {
                   9666:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9667:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9668:                                     push(@newcoowners,$coowner);
                   9669:                                 }
                   9670:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9671:                                     push(@newcoowners,$uname.':'.$udom);
                   9672:                                 }
                   9673:                                 @newcoowners = sort(@newcoowners);
                   9674:                             } else {
                   9675:                                 push(@newcoowners,$uname.':'.$udom);
                   9676:                             }
                   9677:                         } else {
                   9678:                             if ($coursehash{'internal.co-owners'}) {
                   9679:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9680:                                     unless ($coowner eq $uname.':'.$udom) {
                   9681:                                         push(@newcoowners,$coowner);
                   9682:                                     }
                   9683:                                 }
                   9684:                                 unless (@newcoowners > 0) {
                   9685:                                     $delcoowners = 1;
                   9686:                                     $coowners = '';
                   9687:                                 }
                   9688:                             }
                   9689:                         }
                   9690:                         if (@newcoowners || $delcoowners) {
                   9691:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9692:                                             $delcoowners,@newcoowners);
                   9693:                         }
                   9694:                     }
                   9695:                 }
                   9696:             }
                   9697:         }
                   9698:     }
                   9699: }
                   9700: 
                   9701: sub store_coowners {
                   9702:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9703:     my $cid = $cdom.'_'.$cnum;
                   9704:     my ($coowners,$delresult,$putresult);
                   9705:     if (@newcoowners) {
                   9706:         $coowners = join(',',@newcoowners);
                   9707:         my %coownershash = (
                   9708:                             'internal.co-owners' => $coowners,
                   9709:                            );
                   9710:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9711:         if ($putresult eq 'ok') {
                   9712:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9713:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9714:             }
                   9715:         }
                   9716:     }
                   9717:     if ($delcoowners) {
                   9718:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9719:         if ($delresult eq 'ok') {
                   9720:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9721:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9722:             }
                   9723:         }
                   9724:     }
                   9725:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9726:         my %crsinfo =
                   9727:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9728:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9729:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9730:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9731:         }
                   9732:     }
                   9733: }
                   9734: 
1.169     harris41 9735: # -------------------------------------------------- Modify user authentication
1.197     www      9736: # Overrides without validation
                   9737: 
1.169     harris41 9738: sub modifyuserauth {
                   9739:     my ($udom,$uname,$umode,$upass)=@_;
                   9740:     my $uhome=&homeserver($uname,$udom);
1.197     www      9741:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9742:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9743:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9744:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9745:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9746: 		     &escape($upass),$uhome);
1.620     albertel 9747:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9748:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9749:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9750:     &log($udom,,$uname,$uhome,
1.620     albertel 9751:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9752:                                      $env{'user.name'}.', '.$umode.
1.197     www      9753:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9754:     unless ($reply eq 'ok') {
1.197     www      9755:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9756: 	return 'error: '.$reply;
                   9757:     }   
1.170     harris41 9758:     return 'ok';
1.80      www      9759: }
                   9760: 
1.81      www      9761: # --------------------------------------------------------------- Modify a user
1.80      www      9762: 
1.81      www      9763: sub modifyuser {
1.206     matthew  9764:     my ($udom,    $uname, $uid,
                   9765:         $umode,   $upass, $first,
                   9766:         $middle,  $last,  $gene,
1.1058    raeburn  9767:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9768:     $udom= &LONCAPA::clean_domain($udom);
                   9769:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9770:     my $showcandelete = 'none';
                   9771:     if (ref($candelete) eq 'ARRAY') {
                   9772:         if (@{$candelete} > 0) {
                   9773:             $showcandelete = join(', ',@{$candelete});
                   9774:         }
                   9775:     }
1.81      www      9776:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9777:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9778: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9779:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9780:                                      ' desiredhome not specified'). 
1.620     albertel 9781:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9782:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9783:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9784:     my $newuser;
                   9785:     if ($uhome eq 'no_host') {
                   9786:         $newuser = 1;
                   9787:     }
1.80      www      9788: # ----------------------------------------------------------------- Create User
1.406     albertel 9789:     if (($uhome eq 'no_host') && 
                   9790: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9791:         my $unhome='';
1.844     albertel 9792:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9793:             $unhome = $desiredhome;
1.620     albertel 9794: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9795: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9796:         } else { # load balancing routine for determining $unhome
1.81      www      9797:             my $loadm=10000000;
1.841     albertel 9798: 	    my %servers = &get_servers($udom,'library');
                   9799: 	    foreach my $tryserver (keys(%servers)) {
                   9800: 		my $answer=reply('load',$tryserver);
                   9801: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9802: 		    $loadm=$answer;
                   9803: 		    $unhome=$tryserver;
                   9804: 		}
1.80      www      9805: 	    }
                   9806:         }
                   9807:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9808: 	    return 'error: unable to find a home server for '.$uname.
                   9809:                    ' in domain '.$udom;
1.80      www      9810:         }
                   9811:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9812:                          &escape($upass),$unhome);
                   9813: 	unless ($reply eq 'ok') {
                   9814:             return 'error: '.$reply;
                   9815:         }   
1.230     stredwic 9816:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9817:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9818: 	    return 'error: unable verify users home machine.';
1.80      www      9819:         }
1.209     matthew  9820:     }   # End of creation of new user
1.80      www      9821: # ---------------------------------------------------------------------- Add ID
                   9822:     if ($uid) {
                   9823:        $uid=~tr/A-Z/a-z/;
                   9824:        my %uidhash=&idrget($udom,$uname);
1.196     www      9825:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9826:          && (!$forceid)) {
1.80      www      9827: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9828: 	      return 'error: user id "'.$uid.'" does not match '.
                   9829:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9830:           }
                   9831:        } else {
                   9832: 	  &idput($udom,($uname => $uid));
                   9833:        }
                   9834:     }
                   9835: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9836:     my @tmp=&get('environment',
1.899     raeburn  9837: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9838:                     'permanentemail','inststatus'],
1.134     albertel 9839: 		   $udom,$uname);
1.1075    raeburn  9840:     my (%names,%oldnames);
1.313     matthew  9841:     if ($tmp[0] =~ m/^error:.*/) { 
                   9842:         %names=(); 
                   9843:     } else {
                   9844:         %names = @tmp;
1.1075    raeburn  9845:         %oldnames = %names;
1.313     matthew  9846:     }
1.388     www      9847: #
1.1058    raeburn  9848: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9849: # of users did not contain them), do not overwrite existing values
                   9850: # unless field is in $candelete array ref.  
                   9851: #
                   9852: 
                   9853:     my @fields = ('firstname','middlename','lastname','generation',
                   9854:                   'permanentemail','id');
                   9855:     my %newvalues;
                   9856:     if (ref($candelete) eq 'ARRAY') {
                   9857:         foreach my $field (@fields) {
                   9858:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9859:                 if ($field eq 'firstname') {
                   9860:                     $names{$field} = $first;
                   9861:                 } elsif ($field eq 'middlename') {
                   9862:                     $names{$field} = $middle;
                   9863:                 } elsif ($field eq 'lastname') {
                   9864:                     $names{$field} = $last;
                   9865:                 } elsif ($field eq 'generation') { 
                   9866:                     $names{$field} = $gene;
                   9867:                 } elsif ($field eq 'permanentemail') {
                   9868:                     $names{$field} = $email;
                   9869:                 } elsif ($field eq 'id') {
                   9870:                     $names{$field}  = $uid;
                   9871:                 }
                   9872:             }
                   9873:         }
                   9874:     }
1.388     www      9875:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9876:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9877:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9878:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9879:     if ($email) {
                   9880:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9881:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9882:     }
1.899     raeburn  9883:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9884:     if (defined($inststatus)) {
                   9885:         $names{'inststatus'} = '';
                   9886:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9887:         if (ref($usertypes) eq 'HASH') {
                   9888:             my @okstatuses; 
                   9889:             foreach my $item (split(/:/,$inststatus)) {
                   9890:                 if (defined($usertypes->{$item})) {
                   9891:                     push(@okstatuses,$item);  
                   9892:                 }
                   9893:             }
                   9894:             if (@okstatuses) {
                   9895:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9896:             }
                   9897:         }
                   9898:     }
1.1075    raeburn  9899:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9900:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9901:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9902:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9903:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9904:     } else {
                   9905:         $logmsg .= ' during self creation';
                   9906:     }
1.1075    raeburn  9907:     my $changed;
                   9908:     if ($newuser) {
                   9909:         $changed = 1;
                   9910:     } else {
                   9911:         foreach my $field (@fields) {
                   9912:             if ($names{$field} ne $oldnames{$field}) {
                   9913:                 $changed = 1;
                   9914:                 last;
                   9915:             }
                   9916:         }
                   9917:     }
                   9918:     unless ($changed) {
                   9919:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9920:         &logthis($logmsg);
                   9921:         return 'ok';
                   9922:     }
                   9923:     my $reply = &put('environment', \%names, $udom,$uname);
                   9924:     if ($reply ne 'ok') { 
                   9925:         return 'error: '.$reply;
                   9926:     }
1.1087    raeburn  9927:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9928:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9929:     }
1.1075    raeburn  9930:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9931:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9932:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9933:     &logthis($logmsg);
1.134     albertel 9934:     return 'ok';
1.80      www      9935: }
                   9936: 
1.81      www      9937: # -------------------------------------------------------------- Modify student
1.80      www      9938: 
1.81      www      9939: sub modifystudent {
                   9940:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9941:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9942:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9943:     if (!$cid) {
1.620     albertel 9944: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9945: 	    return 'not_in_class';
                   9946: 	}
1.80      www      9947:     }
                   9948: # --------------------------------------------------------------- Make the user
1.81      www      9949:     my $reply=&modifyuser
1.209     matthew  9950: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9951:          $desiredhome,$email,$inststatus);
1.80      www      9952:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9953:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9954:     # student's environment
1.297     matthew  9955:     $uid = undef if (!$forceid);
1.455     albertel 9956:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9957: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9958:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9959:     return $reply;
                   9960: }
                   9961: 
                   9962: sub modify_student_enrollment {
1.1172.2.23  raeburn  9963:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9964:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9965:     my ($cdom,$cnum,$chome);
                   9966:     if (!$cid) {
1.620     albertel 9967: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9968: 	    return 'not_in_class';
                   9969: 	}
1.620     albertel 9970: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9971: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9972:     } else {
                   9973: 	($cdom,$cnum)=split(/_/,$cid);
                   9974:     }
1.620     albertel 9975:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9976:     if (!$chome) {
1.457     raeburn  9977: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9978:     }
1.455     albertel 9979:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9980:     # Make sure the user exists
1.81      www      9981:     my $uhome=&homeserver($uname,$udom);
                   9982:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9983: 	return 'error: no such user';
                   9984:     }
1.297     matthew  9985:     # Get student data if we were not given enough information
                   9986:     if (!defined($first)  || $first  eq '' || 
                   9987:         !defined($last)   || $last   eq '' || 
                   9988:         !defined($uid)    || $uid    eq '' || 
                   9989:         !defined($middle) || $middle eq '' || 
                   9990:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9991:         # They did not supply us with enough data to enroll the student, so
                   9992:         # we need to pick up more information.
1.297     matthew  9993:         my %tmp = &get('environment',
1.294     matthew  9994:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9995:                        ,$udom,$uname);
                   9996: 
1.800     albertel 9997:         #foreach my $key (keys(%tmp)) {
                   9998:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9999:         #}
1.294     matthew  10000:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10001:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10002:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10003:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10004:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10005:     }
1.556     albertel 10006:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10007:     my $user = "$uname:$udom";
                   10008:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10009:     my $reply=cput('classlist',
1.1148    raeburn  10010: 		   {$user => 
1.1172.2.76  raeburn  10011: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10012: 		   $cdom,$cnum);
1.1148    raeburn  10013:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10014:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10015:     } else { 
1.81      www      10016: 	return 'error: '.$reply;
                   10017:     }
1.297     matthew  10018:     # Add student role to user
1.83      www      10019:     my $uurl='/'.$cid;
1.81      www      10020:     $uurl=~s/\_/\//g;
                   10021:     if ($usec) {
                   10022: 	$uurl.='/'.$usec;
                   10023:     }
1.1148    raeburn  10024:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10025:                              $selfenroll,$context);
                   10026:     if ($result ne 'ok') {
                   10027:         if ($old_entry{$user} ne '') {
                   10028:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10029:         } else {
                   10030:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10031:         }
                   10032:     }
                   10033:     return $result; 
1.21      www      10034: }
                   10035: 
1.556     albertel 10036: sub format_name {
                   10037:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10038:     my $name;
                   10039:     if ($first ne 'lastname') {
                   10040: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10041:     } else {
                   10042: 	if ($lastname=~/\S/) {
                   10043: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10044: 	    $name=~s/\s+,/,/;
                   10045: 	} else {
                   10046: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10047: 	}
                   10048:     }
                   10049:     $name=~s/^\s+//;
                   10050:     $name=~s/\s+$//;
                   10051:     $name=~s/\s+/ /g;
                   10052:     return $name;
                   10053: }
                   10054: 
1.84      www      10055: # ------------------------------------------------- Write to course preferences
                   10056: 
                   10057: sub writecoursepref {
                   10058:     my ($courseid,%prefs)=@_;
                   10059:     $courseid=~s/^\///;
                   10060:     $courseid=~s/\_/\//g;
                   10061:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10062:     my $chome=homeserver($cnum,$cdomain);
                   10063:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10064: 	return 'error: no such course';
                   10065:     }
                   10066:     my $cstring='';
1.800     albertel 10067:     foreach my $pref (keys(%prefs)) {
                   10068: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10069:     }
1.84      www      10070:     $cstring=~s/\&$//;
                   10071:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10072: }
                   10073: 
                   10074: # ---------------------------------------------------------- Make/modify course
                   10075: 
                   10076: sub createcourse {
1.741     raeburn  10077:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10078:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10079:     $url=&declutter($url);
                   10080:     my $cid='';
1.1028    raeburn  10081:     if ($context eq 'requestcourses') {
                   10082:         my $can_create = 0;
                   10083:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10084:         if ($udom eq $ownerdom) {
                   10085:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10086:                                   $context)) {
                   10087:                 $can_create = 1;
                   10088:             }
                   10089:         } else {
                   10090:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10091:                                            $category);
                   10092:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10093:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10094:                 if (@curr > 0) {
                   10095:                     my @options = qw(approval validate autolimit);
                   10096:                     my $optregex = join('|',@options);
                   10097:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10098:                         $can_create = 1;
                   10099:                     }
                   10100:                 }
                   10101:             }
                   10102:         }
                   10103:         if ($can_create) {
                   10104:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10105:                 unless (&allowed('ccc',$udom)) {
                   10106:                     return 'refused'; 
                   10107:                 }
1.1017    raeburn  10108:             }
                   10109:         } else {
                   10110:             return 'refused';
                   10111:         }
1.1028    raeburn  10112:     } elsif (!&allowed('ccc',$udom)) {
                   10113:         return 'refused';
1.84      www      10114:     }
1.1011    raeburn  10115: # --------------------------------------------------------------- Get Unique ID
                   10116:     my $uname;
                   10117:     if ($cnum =~ /^$match_courseid$/) {
                   10118:         my $chome=&homeserver($cnum,$udom,'true');
                   10119:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10120:             $uname = $cnum;
                   10121:         } else {
1.1038    raeburn  10122:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10123:         }
                   10124:     } else {
1.1038    raeburn  10125:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10126:     }
                   10127:     return $uname if ($uname =~ /^error/);
                   10128: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10129:     if (!defined($course_server)) {
                   10130:         if (defined(&domain($udom,'primary'))) {
                   10131:             $course_server = &domain($udom,'primary');
                   10132:         } else {
                   10133:             $course_server = $env{'user.home'}; 
                   10134:         }
                   10135:     }
                   10136:     my %host_servers =
                   10137:         &Apache::lonnet::get_servers($udom,'library');
                   10138:     unless ($host_servers{$course_server}) {
                   10139:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10140:     }
1.84      www      10141: # ------------------------------------------------------------- Make the course
                   10142:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10143:                       $course_server);
1.84      www      10144:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10145:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10146:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10147: 	return 'error: no such course';
                   10148:     }
1.271     www      10149: # ----------------------------------------------------------------- Course made
1.516     raeburn  10150: # log existence
1.1029    raeburn  10151:     my $now = time;
1.918     raeburn  10152:     my $newcourse = {
                   10153:                     $udom.'_'.$uname => {
1.921     raeburn  10154:                                      description => $description,
                   10155:                                      inst_code   => $inst_code,
                   10156:                                      owner       => $course_owner,
                   10157:                                      type        => $crstype,
1.1029    raeburn  10158:                                      creator     => $env{'user.name'}.':'.
                   10159:                                                     $env{'user.domain'},
                   10160:                                      created     => $now,
                   10161:                                      context     => $context,
1.918     raeburn  10162:                                                 },
                   10163:                     };
1.921     raeburn  10164:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10165: # set toplevel url
1.271     www      10166:     my $topurl=$url;
                   10167:     unless ($nonstandard) {
                   10168: # ------------------------------------------ For standard courses, make top url
                   10169:         my $mapurl=&clutter($url);
1.278     www      10170:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10171:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10172: <map>
                   10173: <resource id="1" type="start"></resource>
                   10174: <resource id="2" src="$mapurl"></resource>
                   10175: <resource id="3" type="finish"></resource>
                   10176: <link index="1" from="1" to="2"></link>
                   10177: <link index="2" from="2" to="3"></link>
                   10178: </map>
                   10179: ENDINITMAP
                   10180:         $topurl=&declutter(
1.638     albertel 10181:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10182:                           );
                   10183:     }
                   10184: # ----------------------------------------------------------- Write preferences
1.84      www      10185:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10186:                      ('description'              => $description,
                   10187:                       'url'                      => $topurl,
                   10188:                       'internal.creator'         => $env{'user.name'}.':'.
                   10189:                                                     $env{'user.domain'},
                   10190:                       'internal.created'         => $now,
                   10191:                       'internal.creationcontext' => $context)
                   10192:                     );
1.84      www      10193:     return '/'.$udom.'/'.$uname;
                   10194: }
                   10195: 
1.1011    raeburn  10196: # ------------------------------------------------------------------- Create ID
                   10197: sub generate_coursenum {
1.1038    raeburn  10198:     my ($udom,$crstype) = @_;
1.1011    raeburn  10199:     my $domdesc = &domain($udom);
                   10200:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10201:     my $first;
                   10202:     if ($crstype eq 'Community') {
                   10203:         $first = '0';
                   10204:     } else {
                   10205:         $first = int(1+rand(9)); 
                   10206:     } 
                   10207:     my $uname=$first.
1.1011    raeburn  10208:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10209:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10210:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10211: # ----------------------------------------------- Make sure that does not exist
                   10212:     my $uhome=&homeserver($uname,$udom,'true');
                   10213:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10214:         if ($crstype eq 'Community') {
                   10215:             $first = '0';
                   10216:         } else {
                   10217:             $first = int(1+rand(9));
                   10218:         }
                   10219:         $uname=$first.
1.1011    raeburn  10220:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10221:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10222:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10223:         $uhome=&homeserver($uname,$udom,'true');
                   10224:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10225:             return 'error: unable to generate unique course-ID';
                   10226:         }
                   10227:     }
                   10228:     return $uname;
                   10229: }
                   10230: 
1.813     albertel 10231: sub is_course {
1.1167    droeschl 10232:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10233:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10234:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10235:     my $uhome=&homeserver($cnum,$cdom);
                   10236:     my $iscourse;
                   10237:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10238:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10239:     } else {
                   10240:         my $hashid = $cdom.':'.$cnum;
                   10241:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10242:         unless (defined($cached)) {
                   10243:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10244:                                         $cnum,undef,undef,'.');
                   10245:             $iscourse = 0;
                   10246:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10247:                 $iscourse = 1;
                   10248:             }
                   10249:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10250:         }
                   10251:     }
                   10252:     return unless($iscourse);
1.1167    droeschl 10253:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10254: }
                   10255: 
1.1015    raeburn  10256: sub store_userdata {
                   10257:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10258:     my $result;
1.1016    raeburn  10259:     if ($datakey ne '') {
1.1013    raeburn  10260:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10261:             if ($udom eq '' || $uname eq '') {
                   10262:                 $udom = $env{'user.domain'};
                   10263:                 $uname = $env{'user.name'};
                   10264:             }
                   10265:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10266:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10267:                 $result = 'error: no_host';
                   10268:             } else {
                   10269:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10270:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10271: 
                   10272:                 my $namevalue='';
                   10273:                 foreach my $key (keys(%{$storehash})) {
                   10274:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10275:                 }
                   10276:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10277:                 unless ($namespace eq 'courserequests') {
                   10278:                     $datakey = &escape($datakey);
                   10279:                 }
1.1105    raeburn  10280:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10281:                                   $namevalue,$uhome);
1.1013    raeburn  10282:             }
                   10283:         } else {
                   10284:             $result = 'error: data to store was not a hash reference'; 
                   10285:         }
                   10286:     } else {
                   10287:         $result= 'error: invalid requestkey'; 
                   10288:     }
                   10289:     return $result;
                   10290: }
                   10291: 
1.21      www      10292: # ---------------------------------------------------------- Assign Custom Role
                   10293: 
                   10294: sub assigncustomrole {
1.957     raeburn  10295:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10296:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10297:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10298: }
                   10299: 
                   10300: # ----------------------------------------------------------------- Revoke Role
                   10301: 
                   10302: sub revokerole {
1.957     raeburn  10303:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10304:     my $now=time;
1.965     raeburn  10305:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10306: }
                   10307: 
                   10308: # ---------------------------------------------------------- Revoke Custom Role
                   10309: 
                   10310: sub revokecustomrole {
1.957     raeburn  10311:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10312:     my $now=time;
1.357     www      10313:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10314:            $deleteflag,$selfenroll,$context);
1.17      www      10315: }
                   10316: 
1.533     banghart 10317: # ------------------------------------------------------------ Disk usage
1.535     albertel 10318: sub diskusage {
1.955     raeburn  10319:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10320:     $directorypath =~ s/\/$//;
                   10321:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10322:                        .&escape($getpropath).':'.&escape($uname).':'
                   10323:                        .&escape($udom),homeserver($uname,$udom));
                   10324:     if ($listing eq 'unknown_cmd') {
                   10325:         if ($getpropath) {
                   10326:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10327:         }
                   10328:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10329:     }
1.514     albertel 10330:     return $listing;
1.512     banghart 10331: }
                   10332: 
1.566     banghart 10333: sub is_locked {
1.1096    raeburn  10334:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10335:     my @check;
                   10336:     my $is_locked;
1.1093    raeburn  10337:     push (@check,$file_name);
1.613     albertel 10338:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10339: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10340:     my ($tmp)=keys(%locked);
                   10341:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10342:     
1.566     banghart 10343:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10344:         $is_locked = 'false';
                   10345:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10346:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10347:                $is_locked = 'true';
1.1096    raeburn  10348:                if (ref($which) eq 'ARRAY') {
                   10349:                    push(@{$which},$entry);
                   10350:                } else {
                   10351:                    last;
                   10352:                }
1.745     raeburn  10353:            }
                   10354:        }
1.566     banghart 10355:     } else {
                   10356:         $is_locked = 'false';
                   10357:     }
1.1093    raeburn  10358:     return $is_locked;
1.566     banghart 10359: }
                   10360: 
1.759     albertel 10361: sub declutter_portfile {
                   10362:     my ($file) = @_;
1.833     albertel 10363:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10364:     return $file;
                   10365: }
                   10366: 
1.559     banghart 10367: # ------------------------------------------------------------- Mark as Read Only
                   10368: 
                   10369: sub mark_as_readonly {
                   10370:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10371:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10372:     my ($tmp)=keys(%current_permissions);
                   10373:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10374:     foreach my $file (@{$files}) {
1.759     albertel 10375: 	$file = &declutter_portfile($file);
1.561     banghart 10376:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10377:     }
1.613     albertel 10378:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10379:     return;
                   10380: }
                   10381: 
1.572     banghart 10382: # ------------------------------------------------------------Save Selected Files
                   10383: 
                   10384: sub save_selected_files {
                   10385:     my ($user, $path, @files) = @_;
                   10386:     my $filename = $user."savedfiles";
1.573     banghart 10387:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10388:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10389:     foreach my $file (@files) {
1.620     albertel 10390:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10391:     }
                   10392:     foreach my $file (@other_files) {
1.574     banghart 10393:         print (OUT $file."\n");
1.572     banghart 10394:     }
1.574     banghart 10395:     close (OUT);
1.572     banghart 10396:     return 'ok';
                   10397: }
                   10398: 
1.574     banghart 10399: sub clear_selected_files {
                   10400:     my ($user) = @_;
                   10401:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10402:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10403:     print (OUT undef);
                   10404:     close (OUT);
                   10405:     return ("ok");    
                   10406: }
                   10407: 
1.572     banghart 10408: sub files_in_path {
                   10409:     my ($user, $path) = @_;
                   10410:     my $filename = $user."savedfiles";
                   10411:     my %return_files;
1.1172.2.96  raeburn  10412:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10413:     while (my $line_in = <IN>) {
1.574     banghart 10414:         chomp ($line_in);
                   10415:         my @paths_and_file = split (m!/!, $line_in);
                   10416:         my $file_part = pop (@paths_and_file);
                   10417:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10418:         $path_part.='/';
                   10419:         my $path_and_file = $path_part.$file_part;
                   10420:         if ($path_part eq $path) {
                   10421:             $return_files{$file_part}= 'selected';
                   10422:         }
                   10423:     }
1.574     banghart 10424:     close (IN);
                   10425:     return (\%return_files);
1.572     banghart 10426: }
                   10427: 
                   10428: # called in portfolio select mode, to show files selected NOT in current directory
                   10429: sub files_not_in_path {
                   10430:     my ($user, $path) = @_;
                   10431:     my $filename = $user."savedfiles";
                   10432:     my @return_files;
                   10433:     my $path_part;
1.1172.2.96  raeburn  10434:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10435:     while (my $line = <IN>) {
1.572     banghart 10436:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10437:         my @paths_and_file = split(m|/|, $line);
                   10438:         my $file_part = pop(@paths_and_file);
                   10439:         chomp($file_part);
                   10440:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10441:         $path_part .= '/';
                   10442:         my $path_and_file = $path_part.$file_part;
                   10443:         if ($path_part ne $path) {
1.800     albertel 10444:             push(@return_files, ($path_and_file));
1.572     banghart 10445:         }
                   10446:     }
1.800     albertel 10447:     close(OUT);
1.574     banghart 10448:     return (@return_files);
1.572     banghart 10449: }
                   10450: 
1.745     raeburn  10451: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10452: 
1.745     raeburn  10453: sub get_portfile_permissions {
                   10454:     my ($domain,$user) = @_;
1.613     albertel 10455:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10456:     my ($tmp)=keys(%current_permissions);
                   10457:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10458:     return \%current_permissions;
                   10459: }
                   10460: 
                   10461: #---------------------------------------------Get portfolio file access controls
                   10462: 
1.749     raeburn  10463: sub get_access_controls {
1.745     raeburn  10464:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10465:     my %access;
                   10466:     my $real_file = $file;
                   10467:     $file =~ s/\.meta$//;
1.745     raeburn  10468:     if (defined($file)) {
1.749     raeburn  10469:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10470:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10471:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10472:             }
                   10473:         }
1.745     raeburn  10474:     } else {
1.749     raeburn  10475:         foreach my $key (keys(%{$current_permissions})) {
                   10476:             if ($key =~ /\0accesscontrol$/) {
                   10477:                 if (defined($group)) {
                   10478:                     if ($key !~ m-^\Q$group\E/-) {
                   10479:                         next;
                   10480:                     }
                   10481:                 }
                   10482:                 my ($fullpath) = split(/\0/,$key);
                   10483:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10484:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10485:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10486:                     }
                   10487:                 }
                   10488:             }
                   10489:         }
                   10490:     }
                   10491:     return %access;
                   10492: }
                   10493: 
                   10494: sub modify_access_controls {
                   10495:     my ($file_name,$changes,$domain,$user)=@_;
                   10496:     my ($outcome,$deloutcome);
                   10497:     my %store_permissions;
                   10498:     my %new_values;
                   10499:     my %new_control;
                   10500:     my %translation;
                   10501:     my @deletions = ();
                   10502:     my $now = time;
                   10503:     if (exists($$changes{'activate'})) {
                   10504:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10505:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10506:             my $numnew = scalar(@newitems);
                   10507:             for (my $i=0; $i<$numnew; $i++) {
                   10508:                 my $newkey = $newitems[$i];
                   10509:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10510:                 if ($newkey =~ /^\d+:/) { 
                   10511:                     $newkey =~ s/^(\d+)/$newid/;
                   10512:                     $translation{$1} = $newid;
                   10513:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10514:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10515:                     $translation{$1} = $newid;
                   10516:                 }
1.749     raeburn  10517:                 $new_values{$file_name."\0".$newkey} = 
                   10518:                                           $$changes{'activate'}{$newitems[$i]};
                   10519:                 $new_control{$newkey} = $now;
                   10520:             }
                   10521:         }
                   10522:     }
                   10523:     my %todelete;
                   10524:     my %changed_items;
                   10525:     foreach my $action ('delete','update') {
                   10526:         if (exists($$changes{$action})) {
                   10527:             if (ref($$changes{$action}) eq 'HASH') {
                   10528:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10529:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10530:                     if ($action eq 'delete') { 
                   10531:                         $todelete{$itemnum} = 1;
                   10532:                     } else {
                   10533:                         $changed_items{$itemnum} = $key;
                   10534:                     }
                   10535:                 }
1.745     raeburn  10536:             }
                   10537:         }
1.749     raeburn  10538:     }
                   10539:     # get lock on access controls for file.
                   10540:     my $lockhash = {
                   10541:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10542:                                                        ':'.$env{'user.domain'},
                   10543:                    }; 
                   10544:     my $tries = 0;
                   10545:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10546:    
1.1172.2.79  raeburn  10547:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10548:         $tries ++;
1.1172.2.79  raeburn  10549:         sleep(0.1);
1.749     raeburn  10550:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10551:     }
                   10552:     if ($gotlock eq 'ok') {
                   10553:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10554:         my ($tmp)=keys(%curr_permissions);
                   10555:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10556:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10557:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10558:             if (ref($curr_controls) eq 'HASH') {
                   10559:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10560:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10561:                     if (defined($todelete{$itemnum})) {
                   10562:                         push(@deletions,$file_name."\0".$control_item);
                   10563:                     } else {
                   10564:                         if (defined($changed_items{$itemnum})) {
                   10565:                             $new_control{$changed_items{$itemnum}} = $now;
                   10566:                             push(@deletions,$file_name."\0".$control_item);
                   10567:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10568:                         } else {
                   10569:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10570:                         }
                   10571:                     }
1.745     raeburn  10572:                 }
                   10573:             }
                   10574:         }
1.970     raeburn  10575:         my ($group);
                   10576:         if (&is_course($domain,$user)) {
                   10577:             ($group,my $file) = split(/\//,$file_name,2);
                   10578:         }
1.749     raeburn  10579:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10580:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10581:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10582:         #  remove lock
                   10583:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10584:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10585:         my $sqlresult =
1.970     raeburn  10586:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10587:                                     $group);
1.749     raeburn  10588:     } else {
                   10589:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10590:     }
1.749     raeburn  10591:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10592: }
                   10593: 
1.827     raeburn  10594: sub make_public_indefinitely {
                   10595:     my ($requrl) = @_;
                   10596:     my $now = time;
                   10597:     my $action = 'activate';
                   10598:     my $aclnum = 0;
                   10599:     if (&is_portfolio_url($requrl)) {
                   10600:         my (undef,$udom,$unum,$file_name,$group) =
                   10601:             &parse_portfolio_url($requrl);
                   10602:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10603:         my %access_controls = &get_access_controls($current_perms,
                   10604:                                                    $group,$file_name);
                   10605:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10606:             my ($num,$scope,$end,$start) = 
                   10607:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10608:             if ($scope eq 'public') {
                   10609:                 if ($start <= $now && $end == 0) {
                   10610:                     $action = 'none';
                   10611:                 } else {
                   10612:                     $action = 'update';
                   10613:                     $aclnum = $num;
                   10614:                 }
                   10615:                 last;
                   10616:             }
                   10617:         }
                   10618:         if ($action eq 'none') {
                   10619:              return 'ok';
                   10620:         } else {
                   10621:             my %changes;
                   10622:             my $newend = 0;
                   10623:             my $newstart = $now;
                   10624:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10625:             $changes{$action}{$newkey} = {
                   10626:                 type => 'public',
                   10627:                 time => {
                   10628:                     start => $newstart,
                   10629:                     end   => $newend,
                   10630:                 },
                   10631:             };
                   10632:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10633:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10634:             return $outcome;
                   10635:         }
                   10636:     } else {
                   10637:         return 'invalid';
                   10638:     }
                   10639: }
                   10640: 
1.745     raeburn  10641: #------------------------------------------------------Get Marked as Read Only
                   10642: 
                   10643: sub get_marked_as_readonly {
                   10644:     my ($domain,$user,$what,$group) = @_;
                   10645:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10646:     my @readonly_files;
1.629     banghart 10647:     my $cmp1=$what;
                   10648:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10649:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10650:         if (defined($group)) {
                   10651:             if ($file_name !~ m-^\Q$group\E/-) {
                   10652:                 next;
                   10653:             }
                   10654:         }
1.561     banghart 10655:         if (ref($value) eq "ARRAY"){
                   10656:             foreach my $stored_what (@{$value}) {
1.629     banghart 10657:                 my $cmp2=$stored_what;
1.759     albertel 10658:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10659:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10660:                 }
1.629     banghart 10661:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10662:                     push(@readonly_files, $file_name);
1.745     raeburn  10663:                     last;
1.563     banghart 10664:                 } elsif (!defined($what)) {
                   10665:                     push(@readonly_files, $file_name);
1.745     raeburn  10666:                     last;
1.561     banghart 10667:                 }
                   10668:             }
1.745     raeburn  10669:         }
1.561     banghart 10670:     }
                   10671:     return @readonly_files;
                   10672: }
1.577     banghart 10673: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10674: 
1.577     banghart 10675: sub get_marked_as_readonly_hash {
1.745     raeburn  10676:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10677:     my %readonly_files;
1.745     raeburn  10678:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10679:         if (defined($group)) {
                   10680:             if ($file_name !~ m-^\Q$group\E/-) {
                   10681:                 next;
                   10682:             }
                   10683:         }
1.577     banghart 10684:         if (ref($value) eq "ARRAY"){
                   10685:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10686:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10687:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10688:                         if ($lock_descriptor eq 'graded') {
                   10689:                             $readonly_files{$file_name} = 'graded';
                   10690:                         } elsif ($lock_descriptor eq 'handback') {
                   10691:                             $readonly_files{$file_name} = 'handback';
                   10692:                         } else {
                   10693:                             if (!exists($readonly_files{$file_name})) {
                   10694:                                 $readonly_files{$file_name} = 'locked';
                   10695:                             }
                   10696:                         }
1.745     raeburn  10697:                     }
1.750     banghart 10698:                 } 
1.577     banghart 10699:             }
                   10700:         } 
                   10701:     }
                   10702:     return %readonly_files;
                   10703: }
1.559     banghart 10704: # ------------------------------------------------------------ Unmark as Read Only
                   10705: 
                   10706: sub unmark_as_readonly {
1.629     banghart 10707:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10708:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10709:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10710:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10711:     my $symb_crs = $what;
                   10712:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10713:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10714:     my ($tmp)=keys(%current_permissions);
                   10715:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10716:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10717:     foreach my $file (@readonly_files) {
1.759     albertel 10718: 	my $clean_file = &declutter_portfile($file);
                   10719: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10720: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10721:         my @new_locks;
                   10722:         my @del_keys;
                   10723:         if (ref($current_locks) eq "ARRAY"){
                   10724:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10725:                 my $compare=$locker;
1.749     raeburn  10726:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10727:                     $compare=join('',@{$locker});
1.746     raeburn  10728:                     if ($compare ne $symb_crs) {
                   10729:                         push(@new_locks, $locker);
                   10730:                     }
1.563     banghart 10731:                 }
                   10732:             }
1.650     albertel 10733:             if (scalar(@new_locks) > 0) {
1.563     banghart 10734:                 $current_permissions{$file} = \@new_locks;
                   10735:             } else {
                   10736:                 push(@del_keys, $file);
1.613     albertel 10737:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10738:                 delete($current_permissions{$file});
1.563     banghart 10739:             }
                   10740:         }
1.561     banghart 10741:     }
1.613     albertel 10742:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10743:     return;
                   10744: }
1.512     banghart 10745: 
1.17      www      10746: # ------------------------------------------------------------ Directory lister
                   10747: 
                   10748: sub dirlist {
1.955     raeburn  10749:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10750:     $uri=~s/^\///;
                   10751:     $uri=~s/\/$//;
1.253     stredwic 10752:     my ($udom, $uname);
1.955     raeburn  10753:     if ($getuserdir) {
1.253     stredwic 10754:         $udom = $userdomain;
                   10755:         $uname = $username;
1.955     raeburn  10756:     } else {
                   10757:         (undef,$udom,$uname)=split(/\//,$uri);
                   10758:         if(defined($userdomain)) {
                   10759:             $udom = $userdomain;
                   10760:         }
                   10761:         if(defined($username)) {
                   10762:             $uname = $username;
                   10763:         }
1.253     stredwic 10764:     }
1.955     raeburn  10765:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10766: 
1.955     raeburn  10767:     $dirRoot = $perlvar{'lonDocRoot'};
                   10768:     if (defined($getpropath)) {
                   10769:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10770:         $dirRoot =~ s/\/$//;
1.955     raeburn  10771:     } elsif (defined($getuserdir)) {
                   10772:         my $subdir=$uname.'__';
                   10773:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10774:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10775:                    ."/$udom/$subdir/$uname";
                   10776:     } elsif (defined($alternateRoot)) {
                   10777:         $dirRoot = $alternateRoot;
1.751     banghart 10778:     }
1.253     stredwic 10779: 
                   10780:     if($udom) {
                   10781:         if($uname) {
1.1135    raeburn  10782:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10783:             if ($uhome eq 'no_host') {
                   10784:                 return ([],'no_host');
                   10785:             }
1.955     raeburn  10786:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10787:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10788:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10789:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10790:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10791:             } else {
                   10792:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10793:             }
1.605     matthew  10794:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10795:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10796:                 @listing_results = split(/:/,$listing);
                   10797:             } else {
                   10798:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10799:             }
1.1135    raeburn  10800:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10801:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10802:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10803:                 return ([],$listing);
                   10804:             } else {
                   10805:                 return (\@listing_results);
1.1135    raeburn  10806:             }
1.955     raeburn  10807:         } elsif(!$alternateRoot) {
1.1136    raeburn  10808:             my (%allusers,%listerror);
1.841     albertel 10809: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10810:  	    foreach my $tryserver (keys(%servers)) {
                   10811:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10812:                                   &escape($udom),$tryserver);
                   10813:                 if ($listing eq 'unknown_cmd') {
                   10814: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10815: 				      $udom, $tryserver);
                   10816:                 } else {
                   10817:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10818:                 }
1.841     albertel 10819: 		if ($listing eq 'unknown_cmd') {
                   10820: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10821: 				      $udom, $tryserver);
                   10822: 		    @listing_results = split(/:/,$listing);
                   10823: 		} else {
                   10824: 		    @listing_results =
                   10825: 			map { &unescape($_); } split(/:/,$listing);
                   10826: 		}
1.1136    raeburn  10827:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10828:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10829:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10830:                     $listerror{$tryserver} = $listing;
                   10831:                 } else {
1.841     albertel 10832: 		    foreach my $line (@listing_results) {
                   10833: 			my ($entry) = split(/&/,$line,2);
                   10834: 			$allusers{$entry} = 1;
                   10835: 		    }
                   10836: 		}
1.253     stredwic 10837:             }
1.1136    raeburn  10838:             my @alluserslist=();
1.800     albertel 10839:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10840:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10841:             }
1.1172.2.80  raeburn  10842:             if (!%listerror) {
                   10843:                 # no errors
                   10844:                 return (\@alluserslist);
                   10845:             } elsif (scalar(keys(%servers)) == 1) {
                   10846:                 # one library server, one error
                   10847:                 my ($key) = keys(%listerror);
                   10848:                 return (\@alluserslist, $listerror{$key});
                   10849:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10850:                 # con_lost indicates that we might miss data from at least one
                   10851:                 # library server
                   10852:                 return (\@alluserslist, 'con_lost');
                   10853:             } else {
                   10854:                 # multiple library servers and no con_lost -> data should be
                   10855:                 # complete.
                   10856:                 return (\@alluserslist);
                   10857:             }
                   10858: 
1.253     stredwic 10859:         } else {
1.1136    raeburn  10860:             return ([],'missing username');
1.253     stredwic 10861:         }
1.955     raeburn  10862:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10863:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10864:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10865:         return (\@all_domains);
1.955     raeburn  10866:     } else {
1.1136    raeburn  10867:         return ([],'missing domain');
1.275     stredwic 10868:     }
                   10869: }
                   10870: 
                   10871: # --------------------------------------------- GetFileTimestamp
                   10872: # This function utilizes dirlist and returns the date stamp for
                   10873: # when it was last modified.  It will also return an error of -1
                   10874: # if an error occurs
                   10875: 
                   10876: sub GetFileTimestamp {
1.955     raeburn  10877:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10878:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10879:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10880:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10881:                                     undef,$getuserdir);
                   10882:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10883:         return -1;
                   10884:     }
                   10885:     if (ref($fileref) eq 'ARRAY') {
                   10886:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10887:         # @stats contains first the filename, then the stat output
                   10888:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10889:     } else {
                   10890:         return -1;
1.253     stredwic 10891:     }
1.26      www      10892: }
                   10893: 
1.712     albertel 10894: sub stat_file {
                   10895:     my ($uri) = @_;
1.787     albertel 10896:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10897: 
1.955     raeburn  10898:     my ($udom,$uname,$file);
1.712     albertel 10899:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10900: 	($udom,$uname,$file) =
1.811     albertel 10901: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10902: 	$file = 'userfiles/'.$file;
                   10903:     }
                   10904:     if ($uri =~ m-^/res/-) {
                   10905: 	($udom,$uname) = 
1.807     albertel 10906: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10907: 	$file = $uri;
                   10908:     }
                   10909: 
                   10910:     if (!$udom || !$uname || !$file) {
                   10911: 	# unable to handle the uri
                   10912: 	return ();
                   10913:     }
1.956     raeburn  10914:     my $getpropath;
                   10915:     if ($file =~ /^userfiles\//) {
                   10916:         $getpropath = 1;
                   10917:     }
1.1136    raeburn  10918:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10919:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10920:         return ();
                   10921:     } else {
                   10922:         if (ref($listref) eq 'ARRAY') {
                   10923:             my @stats = split('&',$listref->[0]);
                   10924: 	    shift(@stats); #filename is first
                   10925: 	    return @stats;
                   10926:         }
1.712     albertel 10927:     }
                   10928:     return ();
                   10929: }
                   10930: 
1.26      www      10931: # -------------------------------------------------------- Value of a Condition
                   10932: 
1.713     albertel 10933: # gets the value of a specific preevaluated condition
                   10934: #    stored in the string  $env{user.state.<cid>}
                   10935: # or looks up a condition reference in the bighash and if if hasn't
                   10936: # already been evaluated recurses into docondval to get the value of
                   10937: # the condition, then memoizing it to 
                   10938: #   $env{user.state.<cid>.<condition>}
1.40      www      10939: sub directcondval {
                   10940:     my $number=shift;
1.620     albertel 10941:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10942: 	&Apache::lonuserstate::evalstate();
                   10943:     }
1.713     albertel 10944:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10945: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10946:     } elsif ($number =~ /^_/) {
                   10947: 	my $sub_condition;
                   10948: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10949: 		&GDBM_READER(),0640)) {
                   10950: 	    $sub_condition=$bighash{'conditions'.$number};
                   10951: 	    untie(%bighash);
                   10952: 	}
                   10953: 	my $value = &docondval($sub_condition);
1.949     raeburn  10954: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10955: 	return $value;
                   10956:     }
1.620     albertel 10957:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10958:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10959:     } else {
                   10960:        return 2;
                   10961:     }
                   10962: }
                   10963: 
1.713     albertel 10964: # get the collection of conditions for this resource
1.26      www      10965: sub condval {
                   10966:     my $condidx=shift;
1.54      www      10967:     my $allpathcond='';
1.713     albertel 10968:     foreach my $cond (split(/\|/,$condidx)) {
                   10969: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10970: 	    $allpathcond.=
                   10971: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10972: 	}
1.191     harris41 10973:     }
1.54      www      10974:     $allpathcond=~s/\|$//;
1.713     albertel 10975:     return &docondval($allpathcond);
                   10976: }
                   10977: 
                   10978: #evaluates an expression of conditions
                   10979: sub docondval {
                   10980:     my ($allpathcond) = @_;
                   10981:     my $result=0;
                   10982:     if ($env{'request.course.id'}
                   10983: 	&& defined($allpathcond)) {
                   10984: 	my $operand='|';
                   10985: 	my @stack;
                   10986: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10987: 	    if ($chunk eq '(') {
                   10988: 		push @stack,($operand,$result);
                   10989: 	    } elsif ($chunk eq ')') {
                   10990: 		my $before=pop @stack;
                   10991: 		if (pop @stack eq '&') {
                   10992: 		    $result=$result>$before?$before:$result;
                   10993: 		} else {
                   10994: 		    $result=$result>$before?$result:$before;
                   10995: 		}
                   10996: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10997: 		$operand=$chunk;
                   10998: 	    } else {
                   10999: 		my $new=directcondval($chunk);
                   11000: 		if ($operand eq '&') {
                   11001: 		    $result=$result>$new?$new:$result;
                   11002: 		} else {
                   11003: 		    $result=$result>$new?$result:$new;
                   11004: 		}
                   11005: 	    }
                   11006: 	}
1.26      www      11007:     }
                   11008:     return $result;
1.421     albertel 11009: }
                   11010: 
                   11011: # ---------------------------------------------------- Devalidate courseresdata
                   11012: 
                   11013: sub devalidatecourseresdata {
                   11014:     my ($coursenum,$coursedomain)=@_;
                   11015:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11016:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11017: }
                   11018: 
1.763     www      11019: 
1.200     www      11020: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11021: #
                   11022: #  Parameters:
                   11023: #      $coursenum    - Number of the course.
                   11024: #      $coursedomain - Domain at which the course was created.
                   11025: #  Returns:
                   11026: #     A hash of the course parameters along (I think) with timestamps
                   11027: #     and version info.
1.877     foxr     11028: 
1.624     albertel 11029: sub get_courseresdata {
                   11030:     my ($coursenum,$coursedomain)=@_;
1.200     www      11031:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11032:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11033:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11034:     my %dumpreply;
1.417     albertel 11035:     unless (defined($cached)) {
1.624     albertel 11036: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11037: 	$result=\%dumpreply;
1.251     albertel 11038: 	my ($tmp) = keys(%dumpreply);
                   11039: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11040: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11041: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11042: 	    return $tmp;
1.416     albertel 11043: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11044: 	    $result=undef;
1.599     albertel 11045: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11046: 	}
                   11047:     }
1.624     albertel 11048:     return $result;
                   11049: }
                   11050: 
1.633     albertel 11051: sub devalidateuserresdata {
                   11052:     my ($uname,$udom)=@_;
                   11053:     my $hashid="$udom:$uname";
                   11054:     &devalidate_cache_new('userres',$hashid);
                   11055: }
                   11056: 
1.624     albertel 11057: sub get_userresdata {
                   11058:     my ($uname,$udom)=@_;
                   11059:     #most student don\'t have any data set, check if there is some data
                   11060:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11061: 
                   11062:     my $hashid="$udom:$uname";
                   11063:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11064:     if (!defined($cached)) {
                   11065: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11066: 	$result=\%resourcedata;
                   11067: 	&do_cache_new('userres',$hashid,$result,600);
                   11068:     }
                   11069:     my ($tmp)=keys(%$result);
                   11070:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11071: 	return $result;
                   11072:     }
                   11073:     #error 2 occurs when the .db doesn't exist
                   11074:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11075:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11076: 	    &logthis("<font color=\"blue\">WARNING:".
                   11077: 		     " Trying to get resource data for ".
                   11078: 		     $uname." at ".$udom.": ".
                   11079: 		     $tmp."</font>");
                   11080:         }
1.624     albertel 11081:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11082: 	#&EXT_cache_set($udom,$uname);
                   11083: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11084: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11085:     }
                   11086:     return $tmp;
                   11087: }
1.879     foxr     11088: #----------------------------------------------- resdata - return resource data
                   11089: #  Purpose:
                   11090: #    Return resource data for either users or for a course.
                   11091: #  Parameters:
                   11092: #     $name      - Course/user name.
                   11093: #     $domain    - Name of the domain the user/course is registered on.
                   11094: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11095: #     @which     - Array of names of resources desired.
                   11096: #  Returns:
                   11097: #     The value of the first reasource in @which that is found in the
                   11098: #     resource hash.
                   11099: #  Exceptional Conditions:
                   11100: #     If the $type passed in is not valid (not the string 'course' or 
                   11101: #     'user', an undefined  reference is returned.
                   11102: #     If none of the resources are found, an undef is returned
1.624     albertel 11103: sub resdata {
                   11104:     my ($name,$domain,$type,@which)=@_;
                   11105:     my $result;
                   11106:     if ($type eq 'course') {
                   11107: 	$result=&get_courseresdata($name,$domain);
                   11108:     } elsif ($type eq 'user') {
                   11109: 	$result=&get_userresdata($name,$domain);
                   11110:     }
                   11111:     if (!ref($result)) { return $result; }    
1.251     albertel 11112:     foreach my $item (@which) {
1.927     albertel 11113: 	if (defined($result->{$item->[0]})) {
                   11114: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11115: 	}
1.250     albertel 11116:     }
1.291     albertel 11117:     return undef;
1.200     www      11118: }
                   11119: 
1.1172.2.31  raeburn  11120: sub get_numsuppfiles {
                   11121:     my ($cnum,$cdom,$ignorecache)=@_;
                   11122:     my $hashid=$cnum.':'.$cdom;
                   11123:     my ($suppcount,$cached);
                   11124:     unless ($ignorecache) {
                   11125:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11126:     }
                   11127:     unless (defined($cached)) {
                   11128:         my $chome=&homeserver($cnum,$cdom);
                   11129:         unless ($chome eq 'no_host') {
                   11130:             ($suppcount,my $errors) = (0,0);
                   11131:             my $suppmap = 'supplemental.sequence';
                   11132:             ($suppcount,$errors) =
                   11133:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11134:         }
                   11135:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11136:     }
                   11137:     return $suppcount;
                   11138: }
                   11139: 
1.379     matthew  11140: #
                   11141: # EXT resource caching routines
                   11142: #
                   11143: 
                   11144: sub clear_EXT_cache_status {
1.383     albertel 11145:     &delenv('cache.EXT.');
1.379     matthew  11146: }
                   11147: 
                   11148: sub EXT_cache_status {
                   11149:     my ($target_domain,$target_user) = @_;
1.383     albertel 11150:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11151:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11152:         # We know already the user has no data
                   11153:         return 1;
                   11154:     } else {
                   11155:         return 0;
                   11156:     }
                   11157: }
                   11158: 
                   11159: sub EXT_cache_set {
                   11160:     my ($target_domain,$target_user) = @_;
1.383     albertel 11161:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11162:     #&appenv({$cachename => time});
1.379     matthew  11163: }
                   11164: 
1.28      www      11165: # --------------------------------------------------------- Value of a Variable
1.58      www      11166: sub EXT {
1.715     albertel 11167: 
1.1172.2.28  raeburn  11168:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11169:     unless ($varname) { return ''; }
1.218     albertel 11170:     #get real user name/domain, courseid and symb
                   11171:     my $courseid;
1.359     albertel 11172:     my $publicuser;
1.427     www      11173:     if ($symbparm) {
                   11174: 	$symbparm=&get_symb_from_alias($symbparm);
                   11175:     }
1.218     albertel 11176:     if (!($uname && $udom)) {
1.790     albertel 11177:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11178:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11179:     } else {
1.620     albertel 11180: 	$courseid=$env{'request.course.id'};
1.218     albertel 11181:     }
1.48      www      11182:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11183:     my $rest;
1.320     albertel 11184:     if (defined($therest[0])) {
1.48      www      11185:        $rest=join('.',@therest);
                   11186:     } else {
                   11187:        $rest='';
                   11188:     }
1.320     albertel 11189: 
1.57      www      11190:     my $qualifierrest=$qualifier;
                   11191:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11192:     my $spacequalifierrest=$space;
                   11193:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11194:     if ($realm eq 'user') {
1.48      www      11195: # --------------------------------------------------------------- user.resource
                   11196: 	if ($space eq 'resource') {
1.651     albertel 11197: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11198: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11199: 		 &&
1.744     albertel 11200: 		 ($symbparm eq &symbread()) ) {	
                   11201: 		# if we are in the middle of processing the resource the
                   11202: 		# get the value we are planning on committing
                   11203:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11204:                     return $Apache::lonhomework::results{$qualifierrest};
                   11205:                 } else {
                   11206:                     return $Apache::lonhomework::history{$qualifierrest};
                   11207:                 }
1.335     albertel 11208: 	    } else {
1.359     albertel 11209: 		my %restored;
1.620     albertel 11210: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11211: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11212: 		} else {
                   11213: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11214: 		}
1.335     albertel 11215: 		return $restored{$qualifierrest};
                   11216: 	    }
1.48      www      11217: # ----------------------------------------------------------------- user.access
                   11218:         } elsif ($space eq 'access') {
1.218     albertel 11219: 	    # FIXME - not supporting calls for a specific user
1.48      www      11220:             return &allowed($qualifier,$rest);
                   11221: # ------------------------------------------ user.preferences, user.environment
                   11222:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11223: 	    if (($uname eq $env{'user.name'}) &&
                   11224: 		($udom eq $env{'user.domain'})) {
                   11225: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11226: 	    } else {
1.359     albertel 11227: 		my %returnhash;
                   11228: 		if (!$publicuser) {
                   11229: 		    %returnhash=&userenvironment($udom,$uname,
                   11230: 						 $qualifierrest);
                   11231: 		}
1.218     albertel 11232: 		return $returnhash{$qualifierrest};
                   11233: 	    }
1.48      www      11234: # ----------------------------------------------------------------- user.course
                   11235:         } elsif ($space eq 'course') {
1.218     albertel 11236: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11237:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11238: # ------------------------------------------------------------------- user.role
                   11239:         } elsif ($space eq 'role') {
1.218     albertel 11240: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11241:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11242:             if ($qualifier eq 'value') {
                   11243: 		return $role;
                   11244:             } elsif ($qualifier eq 'extent') {
                   11245:                 return $where;
                   11246:             }
                   11247: # ----------------------------------------------------------------- user.domain
                   11248:         } elsif ($space eq 'domain') {
1.218     albertel 11249:             return $udom;
1.48      www      11250: # ------------------------------------------------------------------- user.name
                   11251:         } elsif ($space eq 'name') {
1.218     albertel 11252:             return $uname;
1.48      www      11253: # ---------------------------------------------------- Any other user namespace
1.29      www      11254:         } else {
1.359     albertel 11255: 	    my %reply;
                   11256: 	    if (!$publicuser) {
                   11257: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11258: 	    }
                   11259: 	    return $reply{$qualifierrest};
1.48      www      11260:         }
1.236     www      11261:     } elsif ($realm eq 'query') {
                   11262: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11263:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11264: 						[$spacequalifierrest]);
1.620     albertel 11265: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11266:    } elsif ($realm eq 'request') {
1.48      www      11267: # ------------------------------------------------------------- request.browser
                   11268:         if ($space eq 'browser') {
1.1145    bisitz   11269:             return $env{'browser.'.$qualifier};
1.57      www      11270: # ------------------------------------------------------------ request.filename
                   11271:         } else {
1.620     albertel 11272:             return $env{'request.'.$spacequalifierrest};
1.29      www      11273:         }
1.28      www      11274:     } elsif ($realm eq 'course') {
1.48      www      11275: # ---------------------------------------------------------- course.description
1.620     albertel 11276:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11277:     } elsif ($realm eq 'resource') {
1.165     www      11278: 
1.620     albertel 11279: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11280: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11281: 	}
1.693     albertel 11282: 
1.1172.2.30  raeburn  11283:         if ($qualifier eq '') {
                   11284: 	    if ($space eq 'title') {
                   11285: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11286: 	        return &gettitle($symbparm);
                   11287: 	    }
1.693     albertel 11288: 	
1.1172.2.30  raeburn  11289: 	    if ($space eq 'map') {
                   11290: 	        my ($map) = &decode_symb($symbparm);
                   11291: 	        return &symbread($map);
                   11292: 	    }
                   11293:             if ($space eq 'maptitle') {
                   11294:                 my ($map) = &decode_symb($symbparm);
                   11295:                 return &gettitle($map);
                   11296:             }
                   11297: 	    if ($space eq 'filename') {
                   11298: 	        if ($symbparm) {
                   11299: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11300: 	        }
                   11301: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11302: 	    }
1.1172.2.30  raeburn  11303: 
                   11304:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11305:                 if ($space eq 'visibleparts') {
                   11306:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11307:                     my $item;
                   11308:                     if (ref($navmap)) {
                   11309:                         my $res = $navmap->getBySymb($symbparm);
                   11310:                         my $parts = $res->parts();
                   11311:                         if (ref($parts) eq 'ARRAY') {
                   11312:                             $item = join(',',@{$parts});
                   11313:                         }
                   11314:                         undef($navmap);
                   11315:                     }
                   11316:                     return $item;
                   11317:                 }
                   11318:             }
                   11319:         }
1.693     albertel 11320: 
                   11321: 	my ($section, $group, @groups);
1.593     albertel 11322: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11323:         if (($courseid eq '') && ($cid)) {
                   11324:             $courseid = $cid;
                   11325:         }
                   11326: 	if (($symbparm && $courseid) && 
                   11327: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11328: 
1.218     albertel 11329: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11330: 
1.60      www      11331: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11332: 	    my $symbp=$symbparm;
1.735     albertel 11333: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11334: 
                   11335: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11336: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11337: 
1.620     albertel 11338: 	    if (($env{'user.name'} eq $uname) &&
                   11339: 		($env{'user.domain'} eq $udom)) {
                   11340: 		$section=$env{'request.course.sec'};
1.733     raeburn  11341:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11342:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11343: 	    } else {
1.539     albertel 11344: 		if (! defined($usection)) {
1.551     albertel 11345: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11346: 		} else {
                   11347: 		    $section = $usection;
                   11348: 		}
1.733     raeburn  11349:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11350: 	    }
                   11351: 
                   11352: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11353: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11354: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11355: 
1.593     albertel 11356: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11357: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11358: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11359: 
1.60      www      11360: # ----------------------------------------------------------- first, check user
1.624     albertel 11361: 
                   11362: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11363: 				       ([$courselevelr,'resource'],
                   11364: 					[$courselevelm,'map'     ],
                   11365: 					[$courselevel, 'course'  ]));
1.931     albertel 11366: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11367: 
1.594     albertel 11368: # ------------------------------------------------ second, check some of course
1.684     raeburn  11369:             my $coursereply;
1.691     raeburn  11370:             if (@groups > 0) {
                   11371:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11372:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11373:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11374:             }
1.96      www      11375: 
1.684     raeburn  11376: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11377: 				  $env{'course.'.$courseid.'.domain'},
                   11378: 				  'course',
                   11379: 				  ([$seclevelr,   'resource'],
                   11380: 				   [$seclevelm,   'map'     ],
                   11381: 				   [$seclevel,    'course'  ],
                   11382: 				   [$courselevelr,'resource']));
                   11383: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11384: 
1.60      www      11385: # ------------------------------------------------------ third, check map parms
1.218     albertel 11386: 	    my %parmhash=();
                   11387: 	    my $thisparm='';
                   11388: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11389: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11390: 		    &GDBM_READER(),0640)) {
1.218     albertel 11391: 		$thisparm=$parmhash{$symbparm};
                   11392: 		untie(%parmhash);
                   11393: 	    }
1.927     albertel 11394: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11395: 	}
1.594     albertel 11396: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11397: 
1.218     albertel 11398: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11399: 	my $filename;
                   11400: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11401: 	if ($symbparm) {
1.409     www      11402: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11403: 	} else {
1.620     albertel 11404: 	    $filename=$env{'request.filename'};
1.282     albertel 11405: 	}
                   11406: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11407: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11408: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11409: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11410: 
1.927     albertel 11411: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11412: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11413: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11414: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11415: 				     $env{'course.'.$courseid.'.domain'},
                   11416: 				     'course',
1.927     albertel 11417: 				     ([$courselevelm,'map'   ],
                   11418: 				      [$courselevel, 'course']));
                   11419: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11420: 	}
1.145     www      11421: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11422: 	unless ($space eq '0') {
1.336     albertel 11423: 	    my @parts=split(/_/,$space);
                   11424: 	    my $id=pop(@parts);
                   11425: 	    my $part=join('_',@parts);
                   11426: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11427: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11428: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11429: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11430: 	}
1.395     albertel 11431: 	if ($recurse) { return undef; }
                   11432: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11433: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11434: # ---------------------------------------------------- Any other user namespace
                   11435:     } elsif ($realm eq 'environment') {
                   11436: # ----------------------------------------------------------------- environment
1.620     albertel 11437: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11438: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11439: 	} else {
1.770     albertel 11440: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11441: 		return '';
                   11442: 	    }
1.219     albertel 11443: 	    my %returnhash=&userenvironment($udom,$uname,
                   11444: 					    $spacequalifierrest);
                   11445: 	    return $returnhash{$spacequalifierrest};
                   11446: 	}
1.28      www      11447:     } elsif ($realm eq 'system') {
1.48      www      11448: # ----------------------------------------------------------------- system.time
                   11449: 	if ($space eq 'time') {
                   11450: 	    return time;
                   11451:         }
1.696     albertel 11452:     } elsif ($realm eq 'server') {
                   11453: # ----------------------------------------------------------------- system.time
                   11454: 	if ($space eq 'name') {
                   11455: 	    return $ENV{'SERVER_NAME'};
                   11456:         }
1.28      www      11457:     }
1.48      www      11458:     return '';
1.61      www      11459: }
                   11460: 
1.927     albertel 11461: sub get_reply {
                   11462:     my ($reply_value) = @_;
1.940     raeburn  11463:     if (ref($reply_value) eq 'ARRAY') {
                   11464:         if (wantarray) {
                   11465: 	    return @$reply_value;
                   11466:         }
                   11467:         return $reply_value->[0];
                   11468:     } else {
                   11469:         return $reply_value;
1.927     albertel 11470:     }
                   11471: }
                   11472: 
1.691     raeburn  11473: sub check_group_parms {
                   11474:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11475:     my @groupitems = ();
                   11476:     my $resultitem;
1.927     albertel 11477:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11478:     foreach my $group (@{$groups}) {
                   11479:         foreach my $level (@levels) {
1.927     albertel 11480:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11481:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11482:         }
                   11483:     }
                   11484:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11485:                             $env{'course.'.$courseid.'.domain'},
                   11486:                                      'course',@groupitems);
                   11487:     return $coursereply;
                   11488: }
                   11489: 
                   11490: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11491:     my ($courseid,@groups) = @_;
                   11492:     @groups = sort(@groups);
1.691     raeburn  11493:     return @groups;
                   11494: }
                   11495: 
1.395     albertel 11496: sub packages_tab_default {
                   11497:     my ($uri,$varname)=@_;
                   11498:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11499: 
                   11500:     my (@extension,@specifics,$do_default);
                   11501:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11502: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11503: 	if ($pack_type eq 'default') {
                   11504: 	    $do_default=1;
                   11505: 	} elsif ($pack_type eq 'extension') {
                   11506: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11507: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11508: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11509: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11510: 	}
                   11511:     }
                   11512:     # first look for a package that matches the requested part id
                   11513:     foreach my $package (@specifics) {
                   11514: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11515: 	next if ($pack_part ne $part);
                   11516: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11517: 	    return $packagetab{"$pack_type&$name&default"};
                   11518: 	}
                   11519:     }
                   11520:     # look for any possible matching non extension_ package
                   11521:     foreach my $package (@specifics) {
                   11522: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11523: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11524: 	    return $packagetab{"$pack_type&$name&default"};
                   11525: 	}
1.585     albertel 11526: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11527: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11528: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11529: 	}
                   11530:     }
1.738     albertel 11531:     # look for any posible extension_ match
                   11532:     foreach my $package (@extension) {
                   11533: 	my ($package,$pack_type)=@{$package};
                   11534: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11535: 	    return $packagetab{"$pack_type&$name&default"};
                   11536: 	}
                   11537: 	if (defined($packagetab{$package."&$name&default"})) {
                   11538: 	    return $packagetab{$package."&$name&default"};
                   11539: 	}
                   11540:     }
                   11541:     # look for a global default setting
                   11542:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11543: 	return $packagetab{"default&$name&default"};
                   11544:     }
1.395     albertel 11545:     return undef;
                   11546: }
                   11547: 
1.334     albertel 11548: sub add_prefix_and_part {
                   11549:     my ($prefix,$part)=@_;
                   11550:     my $keyroot;
                   11551:     if (defined($prefix) && $prefix !~ /^__/) {
                   11552: 	# prefix that has a part already
                   11553: 	$keyroot=$prefix;
                   11554:     } elsif (defined($prefix)) {
                   11555: 	# prefix that is missing a part
                   11556: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11557:     } else {
                   11558: 	# no prefix at all
                   11559: 	if (defined($part)) { $keyroot='_'.$part; }
                   11560:     }
                   11561:     return $keyroot;
                   11562: }
                   11563: 
1.71      www      11564: # ---------------------------------------------------------------- Get metadata
                   11565: 
1.599     albertel 11566: my %metaentry;
1.1070    www      11567: my %importedpartids;
1.1172.2.99  raeburn  11568: my %importedrespids;
1.71      www      11569: sub metadata {
1.176     www      11570:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11571:     $uri=&declutter($uri);
1.288     albertel 11572:     # if it is a non metadata possible uri return quickly
1.529     albertel 11573:     if (($uri eq '') || 
                   11574: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11575: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11576:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11577: 	return undef;
                   11578:     }
1.1172.2.49  raeburn  11579:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11580: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11581: 	return undef;
1.288     albertel 11582:     }
1.73      www      11583:     my $filename=$uri;
                   11584:     $uri=~s/\.meta$//;
1.172     www      11585: #
                   11586: # Is the metadata already cached?
1.177     www      11587: # Look at timestamp of caching
1.172     www      11588: # Everything is cached by the main uri, libraries are never directly cached
                   11589: #
1.428     albertel 11590:     if (!defined($liburi)) {
1.599     albertel 11591: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11592: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11593:     }
                   11594:     {
1.1069    www      11595: # Imported parts would go here
1.1172.2.99  raeburn  11596:         my @origfiletagids=();
1.1069    www      11597:         my $importedparts=0;
1.1172.2.99  raeburn  11598: 
                   11599: # Imported responseids would go here
                   11600:         my $importedresponses=0;
1.172     www      11601: #
                   11602: # Is this a recursive call for a library?
                   11603: #
1.599     albertel 11604: #	if (! exists($metacache{$uri})) {
                   11605: #	    $metacache{$uri}={};
                   11606: #	}
1.924     albertel 11607: 	my $cachetime = 60*60;
1.171     www      11608:         if ($liburi) {
                   11609: 	    $liburi=&declutter($liburi);
                   11610:             $filename=$liburi;
1.401     bowersj2 11611:         } else {
1.599     albertel 11612: 	    &devalidate_cache_new('meta',$uri);
                   11613: 	    undef(%metaentry);
1.401     bowersj2 11614: 	}
1.140     www      11615:         my %metathesekeys=();
1.73      www      11616:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11617: 	my $metastring;
1.1140    www      11618: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11619: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11620: 	    $metastring = 
1.929     albertel 11621: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11622: 					  ('grade_target' => 'meta'));
                   11623: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11624: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11625:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11626: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11627: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11628: 	    $metastring=&getfile($file);
1.489     albertel 11629: 	}
1.208     albertel 11630:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11631:         my $token;
1.140     www      11632:         undef %metathesekeys;
1.71      www      11633:         while ($token=$parser->get_token) {
1.339     albertel 11634: 	    if ($token->[0] eq 'S') {
                   11635: 		if (defined($token->[2]->{'package'})) {
1.172     www      11636: #
                   11637: # This is a package - get package info
                   11638: #
1.339     albertel 11639: 		    my $package=$token->[2]->{'package'};
                   11640: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11641: 		    if (defined($token->[2]->{'id'})) { 
                   11642: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11643: 		    }
1.599     albertel 11644: 		    if ($metaentry{':packages'}) {
                   11645: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11646: 		    } else {
1.599     albertel 11647: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11648: 		    }
1.736     albertel 11649: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11650: 			my $part=$keyroot;
                   11651: 			$part=~s/^\_//;
1.736     albertel 11652: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11653: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11654: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11655: 			    # ignore package.tab specified default values
                   11656:                             # here &package_tab_default() will fetch those
                   11657: 			    if ($subp eq 'default') { next; }
1.736     albertel 11658: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11659: 			    my $unikey;
                   11660: 			    if ($pack =~ /_0$/) {
                   11661: 				$unikey='parameter_0_'.$name;
                   11662: 				$part=0;
                   11663: 			    } else {
                   11664: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11665: 			    }
1.339     albertel 11666: 			    if ($subp eq 'display') {
                   11667: 				$value.=' [Part: '.$part.']';
                   11668: 			    }
1.599     albertel 11669: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11670: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11671: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11672: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11673: 			    }
1.599     albertel 11674: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11675: 				$metaentry{':'.$unikey}=
                   11676: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11677: 			    }
1.339     albertel 11678: 			}
                   11679: 		    }
                   11680: 		} else {
1.172     www      11681: #
                   11682: # This is not a package - some other kind of start tag
1.339     albertel 11683: #
                   11684: 		    my $entry=$token->[1];
1.1068    www      11685: 		    my $unikey='';
1.175     www      11686: 
1.339     albertel 11687: 		    if ($entry eq 'import') {
1.175     www      11688: #
                   11689: # Importing a library here
1.339     albertel 11690: #
1.1067    www      11691:                         my $location=$parser->get_text('/import');
                   11692:                         my $dir=$filename;
                   11693:                         $dir=~s|[^/]*$||;
                   11694:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11695: 
                   11696:                         my $importid=$token->[2]->{'id'};
1.1068    www      11697:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11698: #
                   11699: # Check metadata for imported file to
                   11700: # see if it contained response items
                   11701: #
                   11702:                         my %currmetaentry = %metaentry;
                   11703:                         my $libresponseorder = &metadata($location,'responseorder');
                   11704:                         my $origfile;
                   11705:                         if ($libresponseorder ne '') {
                   11706:                             if ($#origfiletagids<0) {
                   11707:                                 undef(%importedrespids);
                   11708:                                 undef(%importedpartids);
                   11709:                             }
                   11710:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11711:                             if (@{$importedrespids{$importid}} > 0) {
                   11712:                                 $importedresponses = 1;
                   11713: # We need to get the original file and the imported file to get the response order correct
                   11714: # Load and inspect original file
                   11715:                                 if ($#origfiletagids<0) {
                   11716:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11717:                                     $origfile=&getfile($origfilelocation);
                   11718:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11719:                                 }
                   11720:                             }
                   11721:                         }
                   11722: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11723: # hash populated for imported library file
                   11724:                         %metaentry = %currmetaentry;
                   11725:                         undef(%currmetaentry);
1.1068    www      11726:                         if ($importmode eq 'problem') {
1.1069    www      11727: # Import as problem/response
1.1068    www      11728:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11729:                         } elsif ($importmode eq 'part') {
                   11730: # Import as part(s)
1.1069    www      11731:                            $importedparts=1;
                   11732: # We need to get the original file and the imported file to get the part order correct
                   11733: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11734: # Load and inspect original file if we didn't do that already
                   11735:                            if ($#origfiletagids<0) {
                   11736:                                undef(%importedrespids);
                   11737:                                undef(%importedpartids);
                   11738:                                if ($origfile eq '') {
                   11739:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11740:                                    $origfile=&getfile($origfilelocation);
                   11741:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11742:                                }
1.1070    www      11743:                            }
                   11744: 
1.1069    www      11745: # Load and inspect imported file
                   11746:                            my $impfile=&getfile($location);
                   11747:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11748:                            if ($#impfilepartids>=0) {
                   11749: # This problem had parts
1.1070    www      11750:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11751:                            } else {
                   11752: # Importing by turning a single problem into a problem part
                   11753: # It gets the import-tags ID as part-ID
                   11754:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11755:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11756:                            }
1.1068    www      11757:                         } else {
                   11758: # Normal import
                   11759:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11760:                            if (defined($token->[2]->{'id'})) {
                   11761:                               $unikey.='_'.$token->[2]->{'id'};
                   11762:                            }
1.1067    www      11763:                         }
                   11764: 
1.339     albertel 11765: 			if ($depthcount<20) {
1.736     albertel 11766: 			    my $metadata = 
                   11767: 				&metadata($uri,'keys', $location,$unikey,
                   11768: 					  $depthcount+1);
                   11769: 			    foreach my $meta (split(',',$metadata)) {
                   11770: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11771: 				$metathesekeys{$meta}=1;
1.339     albertel 11772: 			    }
1.1068    www      11773: 			
                   11774:                         }
1.1067    www      11775: 		    } else {
                   11776: #
                   11777: # Not importing, some other kind of non-package, non-library start tag
                   11778: # 
                   11779:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11780:                         if (defined($token->[2]->{'id'})) {
                   11781:                             $unikey.='_'.$token->[2]->{'id'};
                   11782:                         }
1.339     albertel 11783: 			if (defined($token->[2]->{'name'})) { 
                   11784: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11785: 			}
                   11786: 			$metathesekeys{$unikey}=1;
1.736     albertel 11787: 			foreach my $param (@{$token->[3]}) {
                   11788: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11789: 				$token->[2]->{$param};
1.339     albertel 11790: 			}
                   11791: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11792: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11793: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11794: 		 # only ws inside the tag, and not in default, so use default
                   11795: 		 # as value
1.599     albertel 11796: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11797: 			} elsif ( $internaltext =~ /\S/ ) {
                   11798: 		  # something interesting inside the tag
                   11799: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11800: 			} else {
1.908     albertel 11801: 		  # no interesting values, don't set a default
1.339     albertel 11802: 			}
1.172     www      11803: # end of not-a-package not-a-library import
1.339     albertel 11804: 		    }
1.172     www      11805: # end of not-a-package start tag
1.339     albertel 11806: 		}
1.172     www      11807: # the next is the end of "start tag"
1.339     albertel 11808: 	    }
                   11809: 	}
1.483     albertel 11810: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11811: 	$extension = lc($extension);
                   11812: 	if ($extension eq 'htm') { $extension='html'; }
                   11813: 
1.737     albertel 11814: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11815: 	    #no specific packages #how's our extension
                   11816: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11817: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11818: 					 \%metathesekeys);
                   11819: 	}
1.883     albertel 11820: 
                   11821: 	if (!exists($metaentry{':packages'})
                   11822: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11823: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11824: 		#no specific packages well let's get default then
                   11825: 		if ($key!~/^default&/) { next; }
1.488     albertel 11826: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11827: 					     \%metathesekeys);
                   11828: 	    }
                   11829: 	}
1.338     www      11830: # are there custom rights to evaluate
1.599     albertel 11831: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11832: 
1.338     www      11833:     #
                   11834:     # Importing a rights file here
1.339     albertel 11835:     #
                   11836: 	    unless ($depthcount) {
1.599     albertel 11837: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11838: 		my $dir=$filename;
                   11839: 		$dir=~s|[^/]*$||;
                   11840: 		$location=&filelocation($dir,$location);
1.736     albertel 11841: 		my $rights_metadata =
                   11842: 		    &metadata($uri,'keys',$location,'_rights',
                   11843: 			      $depthcount+1);
                   11844: 		foreach my $rights (split(',',$rights_metadata)) {
                   11845: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11846: 		    $metathesekeys{$rights}=1;
1.339     albertel 11847: 		}
                   11848: 	    }
                   11849: 	}
1.737     albertel 11850: 	# uniqifiy package listing
                   11851: 	my %seen;
                   11852: 	my @uniq_packages =
                   11853: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11854: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11855: 
1.1172.2.99  raeburn  11856:         if (($importedresponses) || ($importedparts)) {
                   11857:             if ($importedparts) {
1.1070    www      11858: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11859:                 $metaentry{':partorder'}='';
                   11860:                 $metathesekeys{'partorder'}=1;
                   11861:             }
                   11862:             if ($importedresponses) {
                   11863: # We had imported responses and need to rebuild responseorder
                   11864:                 $metaentry{':responseorder'}='';
                   11865:                 $metathesekeys{'responseorder'}=1;
                   11866:             }
                   11867:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11868:                 my $origid = $origfiletagids[$index+1];
                   11869:                 if ($origfiletagids[$index] eq 'part') {
                   11870: # Original part, part of the problem
                   11871:                     if ($importedparts) {
                   11872:                         $metaentry{':partorder'}.=','.$origid;
                   11873:                     }
                   11874:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11875:                     if ($importedparts) {
                   11876: # We have imported parts at this position
                   11877:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11878:                     }
                   11879:                     if ($importedresponses) {
                   11880: # We have imported responses at this position
                   11881:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11882:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11883:                         }
                   11884:                     }
                   11885:                 } else {
                   11886: # Original response item, part of the problem
                   11887:                     if ($importedresponses) {
                   11888:                         $metaentry{':responseorder'}.=','.$origid;
                   11889:                     }
                   11890:                 }
                   11891:             }
                   11892:             if ($importedparts) {
                   11893:                 $metaentry{':partorder'}=~s/^\,//;
                   11894:             }
                   11895:             if ($importedresponses) {
                   11896:                 $metaentry{':responseorder'}=~s/^\,//;
                   11897:             }
1.1070    www      11898:         }
                   11899: 
1.737     albertel 11900: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11901: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11902: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11903: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11904: # this is the end of "was not already recently cached
1.71      www      11905:     }
1.599     albertel 11906:     return $metaentry{':'.$what};
1.261     albertel 11907: }
                   11908: 
1.488     albertel 11909: sub metadata_create_package_def {
1.483     albertel 11910:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11911:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11912:     if ($subp eq 'default') { next; }
                   11913:     
1.599     albertel 11914:     if (defined($metaentry{':packages'})) {
                   11915: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11916:     } else {
1.599     albertel 11917: 	$metaentry{':packages'}=$package;
1.483     albertel 11918:     }
                   11919:     my $value=$packagetab{$key};
                   11920:     my $unikey;
                   11921:     $unikey='parameter_0_'.$name;
1.599     albertel 11922:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11923:     $$metathesekeys{$unikey}=1;
1.599     albertel 11924:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11925: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11926:     }
1.599     albertel 11927:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11928: 	$metaentry{':'.$unikey}=
                   11929: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11930:     }
                   11931: }
                   11932: 
1.261     albertel 11933: sub metadata_generate_part0 {
                   11934:     my ($metadata,$metacache,$uri) = @_;
                   11935:     my %allnames;
1.737     albertel 11936:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11937: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11938: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11939: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11940: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11941: 	    $allnames{$name}=$part;
                   11942: 	  }
                   11943: 	}
                   11944:     }
                   11945:     foreach my $name (keys(%allnames)) {
                   11946:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11947:       my $key=":parameter_0_$name";
1.261     albertel 11948:       $$metacache{"$key.part"}='0';
                   11949:       $$metacache{"$key.name"}=$name;
1.428     albertel 11950:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11951: 					   $allnames{$name}.'_'.$name.
                   11952: 					   '.type'};
1.428     albertel 11953:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11954: 			     '.display'};
1.644     www      11955:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11956:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11957:       $$metacache{"$key.display"}=$olddis;
                   11958:     }
1.71      www      11959: }
                   11960: 
1.764     albertel 11961: # ------------------------------------------------------ Devalidate title cache
                   11962: 
                   11963: sub devalidate_title_cache {
                   11964:     my ($url)=@_;
                   11965:     if (!$env{'request.course.id'}) { return; }
                   11966:     my $symb=&symbread($url);
                   11967:     if (!$symb) { return; }
                   11968:     my $key=$env{'request.course.id'}."\0".$symb;
                   11969:     &devalidate_cache_new('title',$key);
                   11970: }
                   11971: 
1.1014    droeschl 11972: # ------------------------------------------------- Get the title of a course
                   11973: 
                   11974: sub current_course_title {
                   11975:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11976: }
1.301     www      11977: # ------------------------------------------------- Get the title of a resource
                   11978: 
                   11979: sub gettitle {
                   11980:     my $urlsymb=shift;
                   11981:     my $symb=&symbread($urlsymb);
1.534     albertel 11982:     if ($symb) {
1.620     albertel 11983: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11984: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11985: 	if (defined($cached)) { 
                   11986: 	    return $result;
                   11987: 	}
1.534     albertel 11988: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11989: 	my $title='';
1.907     albertel 11990: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11991: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11992: 	} else {
                   11993: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11994: 		    &GDBM_READER(),0640)) {
                   11995: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11996: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11997: 		untie(%bighash);
                   11998: 	    }
1.534     albertel 11999: 	}
                   12000: 	$title=~s/\&colon\;/\:/gs;
                   12001: 	if ($title) {
1.1159    www      12002: # Remember both $symb and $title for dynamic metadata
                   12003:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12004:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12005: # Cache this title and then return it
1.599     albertel 12006: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12007: 	}
                   12008: 	$urlsymb=$url;
                   12009:     }
                   12010:     my $title=&metadata($urlsymb,'title');
                   12011:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12012:     return $title;
1.301     www      12013: }
1.613     albertel 12014: 
1.614     albertel 12015: sub get_slot {
                   12016:     my ($which,$cnum,$cdom)=@_;
                   12017:     if (!$cnum || !$cdom) {
1.790     albertel 12018: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12019: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12020: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12021:     }
1.703     albertel 12022:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12023:     my %slotinfo;
                   12024:     if (exists($remembered{$key})) {
                   12025: 	$slotinfo{$which} = $remembered{$key};
                   12026:     } else {
                   12027: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12028: 	&Apache::lonhomework::showhash(%slotinfo);
                   12029: 	my ($tmp)=keys(%slotinfo);
                   12030: 	if ($tmp=~/^error:/) { return (); }
                   12031: 	$remembered{$key} = $slotinfo{$which};
                   12032:     }
1.616     albertel 12033:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12034: 	return %{$slotinfo{$which}};
                   12035:     }
                   12036:     return $slotinfo{$which};
1.614     albertel 12037: }
1.1150    raeburn  12038: 
                   12039: sub get_reservable_slots {
                   12040:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12041:     my $now = time;
                   12042:     my $reservable_info;
                   12043:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12044:     if (exists($remembered{$key})) {
                   12045:         $reservable_info = $remembered{$key};
                   12046:     } else {
                   12047:         my %resv;
                   12048:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12049:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12050:         $reservable_info = \%resv;
                   12051:         $remembered{$key} = $reservable_info;
                   12052:     }
                   12053:     return $reservable_info;
                   12054: }
                   12055: 
                   12056: sub get_course_slots {
                   12057:     my ($cnum,$cdom) = @_;
                   12058:     my $hashid=$cnum.':'.$cdom;
                   12059:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12060:     if (defined($cached)) {
                   12061:         if (ref($result) eq 'HASH') {
                   12062:             return %{$result};
                   12063:         }
                   12064:     } else {
                   12065:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12066:         my ($tmp) = keys(%slots);
                   12067:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12068:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12069:             return %slots;
                   12070:         }
                   12071:     }
                   12072:     return;
                   12073: }
                   12074: 
                   12075: sub devalidate_slots_cache {
                   12076:     my ($cnum,$cdom)=@_;
                   12077:     my $hashid=$cnum.':'.$cdom;
                   12078:     &devalidate_cache_new('allslots',$hashid);
                   12079: }
                   12080: 
1.1172.2.8  raeburn  12081: sub get_coursechange {
                   12082:     my ($cdom,$cnum) = @_;
                   12083:     if ($cdom eq '' || $cnum eq '') {
                   12084:         return unless ($env{'request.course.id'});
                   12085:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12086:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12087:     }
                   12088:     my $hashid=$cdom.'_'.$cnum;
                   12089:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12090:     if ((defined($cached)) && ($change ne '')) {
                   12091:         return $change;
                   12092:     } else {
                   12093:         my %crshash;
                   12094:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12095:         if ($crshash{'internal.contentchange'} eq '') {
                   12096:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12097:             if ($change eq '') {
                   12098:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12099:                 $change = $crshash{'internal.created'};
                   12100:             }
                   12101:         } else {
                   12102:             $change = $crshash{'internal.contentchange'};
                   12103:         }
                   12104:         my $cachetime = 600;
                   12105:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12106:     }
                   12107:     return $change;
                   12108: }
                   12109: 
                   12110: sub devalidate_coursechange_cache {
                   12111:     my ($cnum,$cdom)=@_;
                   12112:     my $hashid=$cnum.':'.$cdom;
                   12113:     &devalidate_cache_new('crschange',$hashid);
                   12114: }
                   12115: 
1.31      www      12116: # ------------------------------------------------- Update symbolic store links
                   12117: 
                   12118: sub symblist {
                   12119:     my ($mapname,%newhash)=@_;
1.438     www      12120:     $mapname=&deversion(&declutter($mapname));
1.31      www      12121:     my %hash;
1.620     albertel 12122:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12123:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12124:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12125: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12126: 		next if ($url eq 'last_known'
                   12127: 			 && $env{'form.no_update_last_known'});
                   12128: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12129: 						    $newhash{$url}->[1],
                   12130: 						    $newhash{$url}->[0]);
1.191     harris41 12131:             }
1.31      www      12132:             if (untie(%hash)) {
                   12133: 		return 'ok';
                   12134:             }
                   12135:         }
                   12136:     }
                   12137:     return 'error';
1.212     www      12138: }
                   12139: 
                   12140: # --------------------------------------------------------------- Verify a symb
                   12141: 
                   12142: sub symbverify {
1.1172.2.11  raeburn  12143:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12144:     my $thisfn=$thisurl;
1.439     www      12145:     $thisfn=&declutter($thisfn);
1.215     www      12146: # direct jump to resource in page or to a sequence - will construct own symbs
                   12147:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12148: # check URL part
1.409     www      12149:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12150: 
1.431     www      12151:     unless ($url eq $thisfn) { return 0; }
1.213     www      12152: 
1.216     www      12153:     $symb=&symbclean($symb);
1.510     www      12154:     $thisurl=&deversion($thisurl);
1.439     www      12155:     $thisfn=&deversion($thisfn);
1.213     www      12156: 
                   12157:     my %bighash;
                   12158:     my $okay=0;
1.431     www      12159: 
1.620     albertel 12160:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12161:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  12162:         my $noclutter;
1.1032    raeburn  12163:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12164:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12165:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12166:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12167:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12168:                 $noclutter = 1;
                   12169:             }
                   12170:         }
                   12171:         my $ids;
                   12172:         if ($noclutter) {
                   12173:             $ids=$bighash{'ids_'.$thisurl};
                   12174:         } else {
                   12175:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12176:         }
1.1102    raeburn  12177:         unless ($ids) {
1.1172.2.13  raeburn  12178:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12179:             $ids=$bighash{$idkey};
1.216     www      12180:         }
                   12181:         if ($ids) {
                   12182: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12183:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12184:                 $symb =~ s/\?.+$//;
                   12185:             }
1.800     albertel 12186: 	    foreach my $id (split(/\,/,$ids)) {
                   12187: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12188:                if (
                   12189:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12190:    eq $symb) {
1.1172.2.11  raeburn  12191:                    if (ref($encstate)) {
                   12192:                        $$encstate = $bighash{'encrypted_'.$id};
                   12193:                    }
1.1172.2.13  raeburn  12194:                    if (($env{'request.role.adv'}) ||
                   12195:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12196:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12197:                        $okay=1;
                   12198:                        last;
                   12199:                    }
                   12200:                }
                   12201:            }
1.216     www      12202:         }
1.213     www      12203: 	untie(%bighash);
                   12204:     }
                   12205:     return $okay;
1.31      www      12206: }
                   12207: 
1.210     www      12208: # --------------------------------------------------------------- Clean-up symb
                   12209: 
                   12210: sub symbclean {
                   12211:     my $symb=shift;
1.568     albertel 12212:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12213: # remove version from map
                   12214:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12215: 
1.210     www      12216: # remove version from URL
                   12217:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12218: 
1.507     www      12219: # remove wrapper
                   12220: 
1.510     www      12221:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12222:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12223:     return $symb;
1.409     www      12224: }
                   12225: 
                   12226: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12227: 
                   12228: sub encode_symb {
                   12229:     my ($map,$resid,$url)=@_;
                   12230:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12231: }
1.409     www      12232: 
                   12233: sub decode_symb {
1.568     albertel 12234:     my $symb=shift;
                   12235:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12236:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12237:     return (&fixversion($map),$resid,&fixversion($url));
                   12238: }
                   12239: 
                   12240: sub fixversion {
                   12241:     my $fn=shift;
1.609     banghart 12242:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12243:     my %bighash;
                   12244:     my $uri=&clutter($fn);
1.620     albertel 12245:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12246: # is this cached?
1.599     albertel 12247:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12248:     if (defined($cached)) { return $result; }
                   12249: # unfortunately not cached, or expired
1.620     albertel 12250:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12251: 	    &GDBM_READER(),0640)) {
                   12252:  	if ($bighash{'version_'.$uri}) {
                   12253:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12254:  	    unless (($version eq 'mostrecent') || 
                   12255: 		    ($version==&getversion($uri))) {
1.440     www      12256:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12257:  	    }
                   12258:  	}
                   12259:  	untie %bighash;
1.413     www      12260:     }
1.599     albertel 12261:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12262: }
                   12263: 
                   12264: sub deversion {
                   12265:     my $url=shift;
                   12266:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12267:     return $url;
1.210     www      12268: }
                   12269: 
1.31      www      12270: # ------------------------------------------------------ Return symb list entry
                   12271: 
                   12272: sub symbread {
1.1172.2.66  raeburn  12273:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12274:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12275:     if (defined($env{$cache_str})) {
                   12276:         if ($ignorecachednull) {
                   12277:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12278:         } else {
                   12279:             return $env{$cache_str};
                   12280:         }
                   12281:     }
1.242     www      12282: # no filename provided? try from environment
1.1172.2.54  raeburn  12283:     unless ($thisfn) {
1.620     albertel 12284:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12285:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12286:         }
                   12287:         $thisfn=$env{'request.filename'};
1.44      www      12288:     }
1.569     albertel 12289:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12290: # is that filename actually a symb? Verify, clean, and return
                   12291:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12292: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12293: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12294: 	}
1.242     www      12295:     }
1.44      www      12296:     $thisfn=declutter($thisfn);
1.31      www      12297:     my %hash;
1.37      www      12298:     my %bighash;
                   12299:     my $syval='';
1.620     albertel 12300:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12301:         my $targetfn = $thisfn;
1.609     banghart 12302:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12303:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12304:         }
1.687     albertel 12305: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12306: 	    $targetfn=$1;
                   12307: 	}
1.620     albertel 12308:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12309:                       &GDBM_READER(),0640)) {
1.481     raeburn  12310: 	    $syval=$hash{$targetfn};
1.37      www      12311:             untie(%hash);
                   12312:         }
                   12313: # ---------------------------------------------------------- There was an entry
                   12314:         if ($syval) {
1.601     albertel 12315: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12316: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12317: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12318: 		    #return $env{$cache_str}='';
1.601     albertel 12319: 		#}    
                   12320: 		#$syval.=$1;
                   12321: 	    #}
1.37      www      12322:         } else {
                   12323: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12324:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12325:                             &GDBM_READER(),0640)) {
1.37      www      12326: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12327:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12328:               unless ($ids) { 
                   12329:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12330:               }
                   12331:               unless ($ids) {
                   12332: # alias?
                   12333: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12334:               }
1.37      www      12335:               if ($ids) {
                   12336: # ------------------------------------------------------------------- Has ID(s)
                   12337:                  my @possibilities=split(/\,/,$ids);
1.39      www      12338:                  if ($#possibilities==0) {
                   12339: # ----------------------------------------------- There is only one possibility
1.37      www      12340: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12341: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12342: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12343:                      if (ref($possibles) eq 'HASH') {
                   12344:                          $possibles->{$syval} = 1;
                   12345:                      }
                   12346:                      if ($checkforblock) {
                   12347:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12348:                          if (@blockers) {
                   12349:                              $syval = '';
                   12350:                              return;
                   12351:                          }
                   12352:                      }
                   12353:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12354: # ------------------------------------------ There is more than one possibility
                   12355:                      my $realpossible=0;
1.800     albertel 12356:                      foreach my $id (@possibilities) {
                   12357: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12358:                          my $canaccess;
                   12359:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12360:                              $canaccess = 1;
                   12361:                          } else {
                   12362:                              $canaccess = &allowed('bre',$file);
                   12363:                          }
                   12364:                          if ($canaccess) {
                   12365:          		     my ($mapid,$resid)=split(/\./,$id);
                   12366:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12367:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12368:                                                              $resid,$thisfn);
                   12369:                                  if (ref($possibles) eq 'HASH') {
                   12370:                                      $possibles->{$syval} = 1;
                   12371:                                  }
                   12372:                                  if ($checkforblock) {
                   12373:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12374:                                      unless (@blockers > 0) {
                   12375:                                          $syval = $poss_syval;
                   12376:                                          $realpossible++;
                   12377:                                      }
                   12378:                                  } else {
                   12379:                                      $syval = $poss_syval;
                   12380:                                      $realpossible++;
                   12381:                                  }
                   12382:                              }
1.39      www      12383: 			 }
1.191     harris41 12384:                      }
1.39      www      12385: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12386:                  } else {
                   12387:                      $syval='';
1.37      www      12388:                  }
                   12389: 	      }
1.1172.2.66  raeburn  12390:               untie(%bighash);
1.481     raeburn  12391:            }
1.31      www      12392:         }
1.62      www      12393:         if ($syval) {
1.620     albertel 12394: 	    return $env{$cache_str}=$syval;
1.62      www      12395:         }
1.31      www      12396:     }
1.949     raeburn  12397:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12398:     return $env{$cache_str}='';
1.31      www      12399: }
                   12400: 
                   12401: # ---------------------------------------------------------- Return random seed
                   12402: 
1.32      www      12403: sub numval {
                   12404:     my $txt=shift;
                   12405:     $txt=~tr/A-J/0-9/;
                   12406:     $txt=~tr/a-j/0-9/;
                   12407:     $txt=~tr/K-T/0-9/;
                   12408:     $txt=~tr/k-t/0-9/;
                   12409:     $txt=~tr/U-Z/0-5/;
                   12410:     $txt=~tr/u-z/0-5/;
                   12411:     $txt=~s/\D//g;
1.564     albertel 12412:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12413:     return int($txt);
1.368     albertel 12414: }
                   12415: 
1.484     albertel 12416: sub numval2 {
                   12417:     my $txt=shift;
                   12418:     $txt=~tr/A-J/0-9/;
                   12419:     $txt=~tr/a-j/0-9/;
                   12420:     $txt=~tr/K-T/0-9/;
                   12421:     $txt=~tr/k-t/0-9/;
                   12422:     $txt=~tr/U-Z/0-5/;
                   12423:     $txt=~tr/u-z/0-5/;
                   12424:     $txt=~s/\D//g;
                   12425:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12426:     my $total;
                   12427:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12428:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12429:     return int($total);
                   12430: }
                   12431: 
1.575     albertel 12432: sub numval3 {
                   12433:     use integer;
                   12434:     my $txt=shift;
                   12435:     $txt=~tr/A-J/0-9/;
                   12436:     $txt=~tr/a-j/0-9/;
                   12437:     $txt=~tr/K-T/0-9/;
                   12438:     $txt=~tr/k-t/0-9/;
                   12439:     $txt=~tr/U-Z/0-5/;
                   12440:     $txt=~tr/u-z/0-5/;
                   12441:     $txt=~s/\D//g;
                   12442:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12443:     my $total;
                   12444:     foreach my $val (@txts) { $total+=$val; }
                   12445:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12446:     return $total;
                   12447: }
                   12448: 
1.675     albertel 12449: sub digest {
                   12450:     my ($data)=@_;
                   12451:     my $digest=&Digest::MD5::md5($data);
                   12452:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12453:     my ($e,$f);
                   12454:     {
                   12455:         use integer;
                   12456:         $e=($a+$b);
                   12457:         $f=($c+$d);
                   12458:         if ($_64bit) {
                   12459:             $e=(($e<<32)>>32);
                   12460:             $f=(($f<<32)>>32);
                   12461:         }
                   12462:     }
                   12463:     if (wantarray) {
                   12464: 	return ($e,$f);
                   12465:     } else {
                   12466: 	my $g;
                   12467: 	{
                   12468: 	    use integer;
                   12469: 	    $g=($e+$f);
                   12470: 	    if ($_64bit) {
                   12471: 		$g=(($g<<32)>>32);
                   12472: 	    }
                   12473: 	}
                   12474: 	return $g;
                   12475:     }
                   12476: }
                   12477: 
1.368     albertel 12478: sub latest_rnd_algorithm_id {
1.675     albertel 12479:     return '64bit5';
1.366     albertel 12480: }
1.32      www      12481: 
1.503     albertel 12482: sub get_rand_alg {
                   12483:     my ($courseid)=@_;
1.790     albertel 12484:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12485:     if ($courseid) {
1.620     albertel 12486: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12487:     }
                   12488:     return &latest_rnd_algorithm_id();
                   12489: }
                   12490: 
1.562     albertel 12491: sub validCODE {
                   12492:     my ($CODE)=@_;
                   12493:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12494:     return 0;
                   12495: }
                   12496: 
1.491     albertel 12497: sub getCODE {
1.620     albertel 12498:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12499:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12500: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12501: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12502: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12503:     }
                   12504:     return undef;
                   12505: }
1.1133    foxr     12506: #
                   12507: #  Determines the random seed for a specific context:
                   12508: #
                   12509: # parameters:
                   12510: #   symb      - in course context the symb for the seed.
                   12511: #   course_id - The course id of the form domain_coursenum.
                   12512: #   domain    - Domain for the user.
                   12513: #   course    - Course for the user.
                   12514: #   cenv      - environment of the course.
                   12515: #
                   12516: # NOTE:
                   12517: #   All parameters are picked out of the environment if missing
                   12518: #   or not defined.
                   12519: #   If a symb cannot be determined the current time is used instead.
                   12520: #
                   12521: #  For a given well defined symb, courside, domain, username,
                   12522: #  and course environment, the seed is reproducible.
                   12523: #
1.31      www      12524: sub rndseed {
1.1133    foxr     12525:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12526:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12527:     if (!defined($symb)) {
1.366     albertel 12528: 	unless ($symb=$wsymb) { return time; }
                   12529:     }
1.1146    foxr     12530:     if (!defined $courseid) { 
                   12531: 	$courseid=$wcourseid; 
                   12532:     }
                   12533:     if (!defined $domain) { $domain=$wdomain; }
                   12534:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12535: 
                   12536:     my $which;
                   12537:     if (defined($cenv->{'rndseed'})) {
                   12538: 	$which = $cenv->{'rndseed'};
                   12539:     } else {
                   12540: 	$which =&get_rand_alg($courseid);
                   12541:     }
1.491     albertel 12542:     if (defined(&getCODE())) {
1.675     albertel 12543: 	if ($which eq '64bit5') {
                   12544: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12545: 	} elsif ($which eq '64bit4') {
1.575     albertel 12546: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12547: 	} else {
                   12548: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12549: 	}
1.675     albertel 12550:     } elsif ($which eq '64bit5') {
                   12551: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12552:     } elsif ($which eq '64bit4') {
                   12553: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12554:     } elsif ($which eq '64bit3') {
                   12555: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12556:     } elsif ($which eq '64bit2') {
                   12557: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12558:     } elsif ($which eq '64bit') {
                   12559: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12560:     }
                   12561:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12562: }
                   12563: 
                   12564: sub rndseed_32bit {
                   12565:     my ($symb,$courseid,$domain,$username)=@_;
                   12566:     {
                   12567: 	use integer;
                   12568: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12569: 	my $symbseed=numval($symb) << 22;
                   12570: 	my $namechck=unpack("%32C*",$username) << 17;
                   12571: 	my $nameseed=numval($username) << 12;
                   12572: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12573: 	my $courseseed=unpack("%32C*",$courseid);
                   12574: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12575: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12576: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12577: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12578: 	return $num;
                   12579:     }
                   12580: }
                   12581: 
                   12582: sub rndseed_64bit {
                   12583:     my ($symb,$courseid,$domain,$username)=@_;
                   12584:     {
                   12585: 	use integer;
                   12586: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12587: 	my $symbseed=numval($symb) << 10;
                   12588: 	my $namechck=unpack("%32S*",$username);
                   12589: 	
                   12590: 	my $nameseed=numval($username) << 21;
                   12591: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12592: 	my $courseseed=unpack("%32S*",$courseid);
                   12593: 	
                   12594: 	my $num1=$symbchck+$symbseed+$namechck;
                   12595: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12596: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12597: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12598: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12599: 	return "$num1,$num2";
1.155     albertel 12600:     }
1.366     albertel 12601: }
                   12602: 
1.443     albertel 12603: sub rndseed_64bit2 {
                   12604:     my ($symb,$courseid,$domain,$username)=@_;
                   12605:     {
                   12606: 	use integer;
                   12607: 	# strings need to be an even # of cahracters long, it it is odd the
                   12608:         # last characters gets thrown away
                   12609: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12610: 	my $symbseed=numval($symb) << 10;
                   12611: 	my $namechck=unpack("%32S*",$username.' ');
                   12612: 	
                   12613: 	my $nameseed=numval($username) << 21;
1.501     albertel 12614: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12615: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12616: 	
                   12617: 	my $num1=$symbchck+$symbseed+$namechck;
                   12618: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12619: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12620: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12621: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12622: 	return "$num1,$num2";
                   12623:     }
                   12624: }
                   12625: 
                   12626: sub rndseed_64bit3 {
                   12627:     my ($symb,$courseid,$domain,$username)=@_;
                   12628:     {
                   12629: 	use integer;
                   12630: 	# strings need to be an even # of cahracters long, it it is odd the
                   12631:         # last characters gets thrown away
                   12632: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12633: 	my $symbseed=numval2($symb) << 10;
                   12634: 	my $namechck=unpack("%32S*",$username.' ');
                   12635: 	
                   12636: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12637: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12638: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12639: 	
                   12640: 	my $num1=$symbchck+$symbseed+$namechck;
                   12641: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12642: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12643: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12644: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12645: 	
1.503     albertel 12646: 	return "$num1:$num2";
1.443     albertel 12647:     }
                   12648: }
                   12649: 
1.575     albertel 12650: sub rndseed_64bit4 {
                   12651:     my ($symb,$courseid,$domain,$username)=@_;
                   12652:     {
                   12653: 	use integer;
                   12654: 	# strings need to be an even # of cahracters long, it it is odd the
                   12655:         # last characters gets thrown away
                   12656: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12657: 	my $symbseed=numval3($symb) << 10;
                   12658: 	my $namechck=unpack("%32S*",$username.' ');
                   12659: 	
                   12660: 	my $nameseed=numval3($username) << 21;
                   12661: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12662: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12663: 	
                   12664: 	my $num1=$symbchck+$symbseed+$namechck;
                   12665: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12666: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12667: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12668: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12669: 	
1.575     albertel 12670: 	return "$num1:$num2";
                   12671:     }
                   12672: }
                   12673: 
1.675     albertel 12674: sub rndseed_64bit5 {
                   12675:     my ($symb,$courseid,$domain,$username)=@_;
                   12676:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12677:     return "$num1:$num2";
                   12678: }
                   12679: 
1.366     albertel 12680: sub rndseed_CODE_64bit {
                   12681:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12682:     {
1.366     albertel 12683: 	use integer;
1.443     albertel 12684: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12685: 	my $symbseed=numval2($symb);
1.491     albertel 12686: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12687: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12688: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12689: 	my $num1=$symbseed+$CODEchck;
                   12690: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12691: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12692: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12693: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12694: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12695: 	return "$num1:$num2";
1.366     albertel 12696:     }
                   12697: }
                   12698: 
1.575     albertel 12699: sub rndseed_CODE_64bit4 {
                   12700:     my ($symb,$courseid,$domain,$username)=@_;
                   12701:     {
                   12702: 	use integer;
                   12703: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12704: 	my $symbseed=numval3($symb);
                   12705: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12706: 	my $CODEseed=numval3(&getCODE());
                   12707: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12708: 	my $num1=$symbseed+$CODEchck;
                   12709: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12710: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12711: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12712: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12713: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12714: 	return "$num1:$num2";
                   12715:     }
                   12716: }
                   12717: 
1.675     albertel 12718: sub rndseed_CODE_64bit5 {
                   12719:     my ($symb,$courseid,$domain,$username)=@_;
                   12720:     my $code = &getCODE();
                   12721:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12722:     return "$num1:$num2";
                   12723: }
                   12724: 
1.366     albertel 12725: sub setup_random_from_rndseed {
                   12726:     my ($rndseed)=@_;
1.503     albertel 12727:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12728: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12729:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12730:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12731:         } else {
                   12732:             &Math::Random::random_set_seed($num1,$num2);
                   12733:         }
1.366     albertel 12734:     } else {
                   12735: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12736:     }
1.36      albertel 12737: }
                   12738: 
1.474     albertel 12739: sub latest_receipt_algorithm_id {
1.835     albertel 12740:     return 'receipt3';
1.474     albertel 12741: }
                   12742: 
1.480     www      12743: sub recunique {
                   12744:     my $fucourseid=shift;
                   12745:     my $unique;
1.835     albertel 12746:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12747: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12748: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12749:     } else {
                   12750: 	$unique=$perlvar{'lonReceipt'};
                   12751:     }
                   12752:     return unpack("%32C*",$unique);
                   12753: }
                   12754: 
                   12755: sub recprefix {
                   12756:     my $fucourseid=shift;
                   12757:     my $prefix;
1.835     albertel 12758:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12759: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12760: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12761:     } else {
                   12762: 	$prefix=$perlvar{'lonHostID'};
                   12763:     }
                   12764:     return unpack("%32C*",$prefix);
                   12765: }
                   12766: 
1.76      www      12767: sub ireceipt {
1.474     albertel 12768:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12769: 
                   12770:     my $return =&recprefix($fucourseid).'-';
                   12771: 
                   12772:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12773: 	$env{'request.state'} eq 'construct') {
                   12774: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12775: 	return $return;
                   12776:     }
                   12777: 
1.76      www      12778:     my $cuname=unpack("%32C*",$funame);
                   12779:     my $cudom=unpack("%32C*",$fudom);
                   12780:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12781:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12782:     my $cunique=&recunique($fucourseid);
1.474     albertel 12783:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12784:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12785: 
1.790     albertel 12786: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12787: 			       
                   12788: 	$return.= ($cunique%$cuname+
                   12789: 		   $cunique%$cudom+
                   12790: 		   $cusymb%$cuname+
                   12791: 		   $cusymb%$cudom+
                   12792: 		   $cucourseid%$cuname+
                   12793: 		   $cucourseid%$cudom+
                   12794: 		   $cpart%$cuname+
                   12795: 		   $cpart%$cudom);
                   12796:     } else {
                   12797: 	$return.= ($cunique%$cuname+
                   12798: 		   $cunique%$cudom+
                   12799: 		   $cusymb%$cuname+
                   12800: 		   $cusymb%$cudom+
                   12801: 		   $cucourseid%$cuname+
                   12802: 		   $cucourseid%$cudom);
                   12803:     }
                   12804:     return $return;
1.76      www      12805: }
                   12806: 
                   12807: sub receipt {
1.474     albertel 12808:     my ($part)=@_;
1.790     albertel 12809:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12810:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12811: }
1.260     ng       12812: 
1.790     albertel 12813: sub whichuser {
                   12814:     my ($passedsymb)=@_;
                   12815:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12816:     if (defined($env{'form.grade_symb'})) {
                   12817: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12818: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12819: 	if (!$allowed &&
                   12820: 	    exists($env{'request.course.sec'}) &&
                   12821: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12822: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12823: 			      '/'.$env{'request.course.sec'});
                   12824: 	}
                   12825: 	if ($allowed) {
                   12826: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12827: 	    $courseid=$tmp_courseid;
                   12828: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12829: 	    ($name)=&get_env_multiple('form.grade_username');
                   12830: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12831: 	}
                   12832:     }
                   12833:     if (!$passedsymb) {
                   12834: 	$symb=&symbread();
                   12835:     } else {
                   12836: 	$symb=$passedsymb;
                   12837:     }
                   12838:     $courseid=$env{'request.course.id'};
                   12839:     $domain=$env{'user.domain'};
                   12840:     $name=$env{'user.name'};
                   12841:     if ($name eq 'public' && $domain eq 'public') {
                   12842: 	if (!defined($env{'form.username'})) {
                   12843: 	    $env{'form.username'}.=time.rand(10000000);
                   12844: 	}
                   12845: 	$name.=$env{'form.username'};
                   12846:     }
                   12847:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12848: 
                   12849: }
                   12850: 
1.36      albertel 12851: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12852: # returns either the contents of the file or 
                   12853: # -1 if the file doesn't exist
1.481     raeburn  12854: #
                   12855: # if the target is a file that was uploaded via DOCS, 
                   12856: # a check will be made to see if a current copy exists on the local server,
                   12857: # if it does this will be served, otherwise a copy will be retrieved from
                   12858: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12859: # the local server.   
1.472     albertel 12860: 
1.36      albertel 12861: sub getfile {
1.538     albertel 12862:     my ($file) = @_;
1.609     banghart 12863:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12864:     &repcopy($file);
                   12865:     return &readfile($file);
                   12866: }
                   12867: 
                   12868: sub repcopy_userfile {
                   12869:     my ($file)=@_;
1.1142    raeburn  12870:     my $londocroot = $perlvar{'lonDocRoot'};
                   12871:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12872:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12873:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12874: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12875:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12876:     if (-e "$file") {
1.828     www      12877: # we already have a local copy, check it out
1.538     albertel 12878: 	my @fileinfo = stat($file);
1.828     www      12879: 	my $rtncode;
                   12880: 	my $info;
1.538     albertel 12881: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12882: 	if ($lwpresp ne 'ok') {
1.828     www      12883: # there is no such file anymore, even though we had a local copy
1.482     albertel 12884: 	    if ($rtncode eq '404') {
1.538     albertel 12885: 		unlink($file);
1.482     albertel 12886: 	    }
                   12887: 	    return -1;
                   12888: 	}
                   12889: 	if ($info < $fileinfo[9]) {
1.828     www      12890: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12891: 	    return 'ok';
1.828     www      12892: 	} else {
                   12893: # the file is outdated, get rid of it
                   12894: 	    unlink($file);
1.482     albertel 12895: 	}
1.828     www      12896:     }
                   12897: # one way or the other, at this point, we don't have the file
                   12898: # construct the correct path for the file
                   12899:     my @parts = ($cdom,$cnum); 
                   12900:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12901: 	push @parts, split(/\//,$1);
                   12902:     }
                   12903:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12904:     foreach my $part (@parts) {
                   12905: 	$path .= '/'.$part;
                   12906: 	if (!-e $path) {
                   12907: 	    mkdir($path,0770);
1.482     albertel 12908: 	}
                   12909:     }
1.828     www      12910: # now the path exists for sure
                   12911: # get a user agent
                   12912:     my $ua=new LWP::UserAgent;
                   12913:     my $transferfile=$file.'.in.transfer';
                   12914: # FIXME: this should flock
                   12915:     if (-e $transferfile) { return 'ok'; }
                   12916:     my $request;
                   12917:     $uri=~s/^\///;
1.980     raeburn  12918:     my $homeserver = &homeserver($cnum,$cdom);
                   12919:     my $protocol = $protocol{$homeserver};
                   12920:     $protocol = 'http' if ($protocol ne 'https');
                   12921:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12922:     my $response=$ua->request($request,$transferfile);
                   12923: # did it work?
                   12924:     if ($response->is_error()) {
                   12925: 	unlink($transferfile);
                   12926: 	&logthis("Userfile repcopy failed for $uri");
                   12927: 	return -1;
                   12928:     }
                   12929: # worked, rename the transfer file
                   12930:     rename($transferfile,$file);
1.607     raeburn  12931:     return 'ok';
1.481     raeburn  12932: }
                   12933: 
1.517     albertel 12934: sub tokenwrapper {
                   12935:     my $uri=shift;
1.980     raeburn  12936:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12937:     $uri=~s|^/||;
1.620     albertel 12938:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12939:     my $token=$1;
1.552     albertel 12940:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12941:     if ($udom && $uname && $file) {
                   12942: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12943:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12944:         my $homeserver = &homeserver($uname,$udom);
                   12945:         my $protocol = $protocol{$homeserver};
                   12946:         $protocol = 'http' if ($protocol ne 'https');
                   12947:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12948:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12949:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12950:     } else {
                   12951:         return '/adm/notfound.html';
                   12952:     }
                   12953: }
                   12954: 
1.828     www      12955: # call with reqtype HEAD: get last modification time
                   12956: # call with reqtype GET: get the file contents
                   12957: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12958: #
1.481     raeburn  12959: sub getuploaded {
                   12960:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12961:     $uri=~s/^\///;
1.980     raeburn  12962:     my $homeserver = &homeserver($cnum,$cdom);
                   12963:     my $protocol = $protocol{$homeserver};
                   12964:     $protocol = 'http' if ($protocol ne 'https');
                   12965:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12966:     my $ua=new LWP::UserAgent;
                   12967:     my $request=new HTTP::Request($reqtype,$uri);
                   12968:     my $response=$ua->request($request);
                   12969:     $$rtncode = $response->code;
1.482     albertel 12970:     if (! $response->is_success()) {
                   12971: 	return 'failed';
                   12972:     }      
                   12973:     if ($reqtype eq 'HEAD') {
1.486     www      12974: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12975:     } elsif ($reqtype eq 'GET') {
                   12976: 	$$info = $response->content;
1.472     albertel 12977:     }
1.482     albertel 12978:     return 'ok';
1.36      albertel 12979: }
                   12980: 
1.481     raeburn  12981: sub readfile {
                   12982:     my $file = shift;
                   12983:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12984:     my $fh;
1.1172.2.96  raeburn  12985:     open($fh,"<",$file);
1.481     raeburn  12986:     my $a='';
1.800     albertel 12987:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12988:     return $a;
                   12989: }
                   12990: 
1.36      albertel 12991: sub filelocation {
1.590     banghart 12992:     my ($dir,$file) = @_;
                   12993:     my $location;
                   12994:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12995: 
                   12996:     if ($file =~ m-^/adm/-) {
                   12997: 	$file=~s-^/adm/wrapper/-/-;
                   12998: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12999:     }
1.882     albertel 13000: 
1.1139    www      13001:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13002:         $location = $file;
1.609     banghart 13003:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13004:         my ($udom,$uname,$filename)=
1.811     albertel 13005:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13006:         my $home=&homeserver($uname,$udom);
                   13007:         my $is_me=0;
                   13008:         my @ids=&current_machine_ids();
                   13009:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13010:         if ($is_me) {
1.1117    foxr     13011:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13012:         } else {
                   13013:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13014:   	      $udom.'/'.$uname.'/'.$filename;
                   13015:         }
1.882     albertel 13016:     } elsif ($file =~ m-^/adm/-) {
                   13017: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13018:     } else {
                   13019:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13020:         $file=~s:^/(res|priv)/:/:;
                   13021:         my $space=$1;
1.590     banghart 13022:         if ( !( $file =~ m:^/:) ) {
                   13023:             $location = $dir. '/'.$file;
                   13024:         } else {
1.1142    raeburn  13025:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13026:         }
1.59      albertel 13027:     }
1.590     banghart 13028:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13029:     while ($location=~m{/\.\./}) {
                   13030: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13031: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13032: 	} else {
                   13033: 	    $location=~ s{/\.\./}{/}g;
                   13034: 	}
                   13035:     } #remove dir/..
1.590     banghart 13036:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13037:     return $location;
1.46      www      13038: }
1.36      albertel 13039: 
1.46      www      13040: sub hreflocation {
                   13041:     my ($dir,$file)=@_;
1.980     raeburn  13042:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13043: 	$file=filelocation($dir,$file);
1.700     albertel 13044:     } elsif ($file=~m-^/adm/-) {
                   13045: 	$file=~s-^/adm/wrapper/-/-;
                   13046: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13047:     }
                   13048:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13049: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13050:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13051: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13052: 	        {/uploaded/$1/$2/}x;
1.46      www      13053:     }
1.913     albertel 13054:     if ($file=~ m{^/userfiles/}) {
                   13055: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13056:     }
1.462     albertel 13057:     return $file;
1.465     albertel 13058: }
                   13059: 
1.1139    www      13060: 
                   13061: 
                   13062: 
                   13063: 
1.465     albertel 13064: sub current_machine_domains {
1.853     albertel 13065:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13066: }
                   13067: 
                   13068: sub machine_domains {
                   13069:     my ($hostname) = @_;
1.465     albertel 13070:     my @domains;
1.838     albertel 13071:     my %hostname = &all_hostnames();
1.465     albertel 13072:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13073: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13074: 	if ($hostname eq $name) {
1.844     albertel 13075: 	    push(@domains,&host_domain($id));
1.465     albertel 13076: 	}
                   13077:     }
                   13078:     return @domains;
                   13079: }
                   13080: 
                   13081: sub current_machine_ids {
1.853     albertel 13082:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13083: }
                   13084: 
                   13085: sub machine_ids {
                   13086:     my ($hostname) = @_;
                   13087:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13088:     my @ids;
1.888     albertel 13089:     my %name_to_host = &all_names();
1.889     albertel 13090:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13091: 	return @{ $name_to_host{$hostname} };
                   13092:     }
                   13093:     return;
1.31      www      13094: }
                   13095: 
1.824     raeburn  13096: sub additional_machine_domains {
                   13097:     my @domains;
1.1172.2.96  raeburn  13098:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13099:     while( my $line = <$fh>) {
                   13100:         $line =~ s/\s//g;
                   13101:         push(@domains,$line);
                   13102:     }
                   13103:     return @domains;
                   13104: }
                   13105: 
                   13106: sub default_login_domain {
                   13107:     my $domain = $perlvar{'lonDefDomain'};
                   13108:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13109:     foreach my $posdom (&current_machine_domains(),
                   13110:                         &additional_machine_domains()) {
                   13111:         if (lc($posdom) eq lc($testdomain)) {
                   13112:             $domain=$posdom;
                   13113:             last;
                   13114:         }
                   13115:     }
                   13116:     return $domain;
                   13117: }
                   13118: 
1.1172.2.106  raeburn  13119: sub shared_institution {
                   13120:     my ($dom) = @_;
                   13121:     my $same_intdom;
                   13122:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13123:     if ($hostintdom ne '') {
                   13124:         my %iphost = &get_iphost();
                   13125:         my $primary_id = &domain($dom,'primary');
                   13126:         my $primary_ip = &get_host_ip($primary_id);
                   13127:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13128:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13129:                 my $intdom = &internet_dom($id);
                   13130:                 if ($intdom eq $hostintdom) {
                   13131:                     $same_intdom = 1;
                   13132:                     last;
                   13133:                 }
                   13134:             }
                   13135:         }
                   13136:     }
                   13137:     return $same_intdom;
                   13138: }
                   13139: 
1.31      www      13140: # ------------------------------------------------------------- Declutters URLs
                   13141: 
                   13142: sub declutter {
                   13143:     my $thisfn=shift;
1.569     albertel 13144:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13145:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13146:         $thisfn=~s{^/home/httpd/html}{};
                   13147:     }
1.31      www      13148:     $thisfn=~s/^\///;
1.697     albertel 13149:     $thisfn=~s|^adm/wrapper/||;
                   13150:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13151:     $thisfn=~s/^res\///;
1.1172    bisitz   13152:     $thisfn=~s/^priv\///;
1.1032    raeburn  13153:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13154:         $thisfn=~s/\?.+$//;
                   13155:     }
1.268     www      13156:     return $thisfn;
                   13157: }
                   13158: 
                   13159: # ------------------------------------------------------------- Clutter up URLs
                   13160: 
                   13161: sub clutter {
                   13162:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13163:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13164: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13165:        $thisfn='/res'.$thisfn; 
                   13166:     }
1.1031    raeburn  13167:     if ($thisfn !~m|^/adm|) {
                   13168: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13169: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13170: 	} else {
                   13171: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13172: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13173: 	    if ($embstyle eq 'ssi'
                   13174: 		|| ($embstyle eq 'hdn')
                   13175: 		|| ($embstyle eq 'rat')
                   13176: 		|| ($embstyle eq 'prv')
                   13177: 		|| ($embstyle eq 'ign')) {
                   13178: 		#do nothing with these
                   13179: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13180: 		|| ($embstyle eq 'emb')
                   13181: 		|| ($embstyle eq 'wrp')) {
                   13182: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13183: 	    } elsif ($embstyle eq 'unk'
                   13184: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13185: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13186: 	    } else {
1.718     www      13187: #		&logthis("Got a blank emb style");
1.695     albertel 13188: 	    }
1.694     albertel 13189: 	}
                   13190:     }
1.31      www      13191:     return $thisfn;
1.12      www      13192: }
                   13193: 
1.787     albertel 13194: sub clutter_with_no_wrapper {
                   13195:     my $uri = &clutter(shift);
                   13196:     if ($uri =~ m-^/adm/-) {
                   13197: 	$uri =~ s-^/adm/wrapper/-/-;
                   13198: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13199:     }
                   13200:     return $uri;
                   13201: }
                   13202: 
1.557     albertel 13203: sub freeze_escape {
                   13204:     my ($value)=@_;
                   13205:     if (ref($value)) {
                   13206: 	$value=&nfreeze($value);
                   13207: 	return '__FROZEN__'.&escape($value);
                   13208:     }
                   13209:     return &escape($value);
                   13210: }
                   13211: 
1.11      www      13212: 
1.557     albertel 13213: sub thaw_unescape {
                   13214:     my ($value)=@_;
                   13215:     if ($value =~ /^__FROZEN__/) {
                   13216: 	substr($value,0,10,undef);
                   13217: 	$value=&unescape($value);
                   13218: 	return &thaw($value);
                   13219:     }
                   13220:     return &unescape($value);
                   13221: }
                   13222: 
1.436     albertel 13223: sub correct_line_ends {
                   13224:     my ($result)=@_;
                   13225:     $$result =~s/\r\n/\n/mg;
                   13226:     $$result =~s/\r/\n/mg;
1.415     albertel 13227: }
1.1       albertel 13228: # ================================================================ Main Program
                   13229: 
1.184     www      13230: sub goodbye {
1.204     albertel 13231:    &logthis("Starting Shut down");
1.443     albertel 13232: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13233:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13234: #converted
1.599     albertel 13235: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13236:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13237: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13238: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13239: #1.1 only
1.870     albertel 13240: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13241: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13242: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13243: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13244:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13245:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13246:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13247:    &flushcourselogs();
                   13248:    &logthis("Shutting down");
                   13249: }
                   13250: 
1.852     albertel 13251: sub get_dns {
1.1172.2.17  raeburn  13252:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13253:     if (!$ignore_cache) {
                   13254: 	my ($content,$cached)=
                   13255: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13256: 	if ($cached) {
1.1172.2.17  raeburn  13257: 	    &$func($content,$hashref);
1.869     albertel 13258: 	    return;
                   13259: 	}
                   13260:     }
                   13261: 
                   13262:     my %alldns;
1.1172.2.96  raeburn  13263:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13264:         foreach my $dns (<$config>) {
                   13265: 	    next if ($dns !~ /^\^(\S*)/x);
                   13266:             my $line = $1;
                   13267:             my ($host,$protocol) = split(/:/,$line);
                   13268:             if ($protocol ne 'https') {
                   13269:                 $protocol = 'http';
                   13270:             }
                   13271: 	    $alldns{$host} = $protocol;
1.979     raeburn  13272:         }
1.1172.2.96  raeburn  13273:         close($config);
1.869     albertel 13274:     }
                   13275:     while (%alldns) {
1.1172.2.52  raeburn  13276: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13277: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13278:         $ua->timeout(30);
1.979     raeburn  13279: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13280: 	my $response=$ua->request($request);
1.979     raeburn  13281:         delete($alldns{$dns});
1.852     albertel 13282: 	next if ($response->is_error());
                   13283: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13284:         unless ($nocache) {
1.1172.2.23  raeburn  13285: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13286:         }
                   13287: 	&$func(\@content,$hashref);
1.869     albertel 13288: 	return;
1.852     albertel 13289:     }
1.871     albertel 13290:     my $which = (split('/',$url))[3];
                   13291:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13292:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13293:         my @content = <$config>;
                   13294:         &$func(\@content,$hashref);
                   13295:     }
1.1172.2.17  raeburn  13296:     return;
                   13297: }
                   13298: 
                   13299: # ------------------------------------------------------Get DNS checksums file
                   13300: sub parse_dns_checksums_tab {
                   13301:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13302:     my $lonhost = $perlvar{'lonHostID'};
                   13303:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13304:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13305:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13306:     my $webconfdir = '/etc/httpd/conf';
                   13307:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13308:         $webconfdir = '/etc/apache2';
                   13309:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13310:         if ($1 >= 10) {
                   13311:             $webconfdir = '/etc/apache2';
                   13312:         }
                   13313:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13314:         if ($1 >= 10.0) {
                   13315:             $webconfdir = '/etc/apache2';
                   13316:         }
                   13317:     }
1.1172.2.17  raeburn  13318:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13319:     my (%chksum,%revnum);
                   13320:     if (ref($lines) eq 'ARRAY') {
                   13321:         chomp(@{$lines});
1.1172.2.34  raeburn  13322:         my $version = shift(@{$lines});
                   13323:         if ($version eq $release) {
1.1172.2.17  raeburn  13324:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13325:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13326:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13327:                     if ($webconfdir eq '/etc/apache2') {
                   13328:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13329:                     }
                   13330:                 }
1.1172.2.34  raeburn  13331:                 $chksum{$file} = $shasum;
                   13332:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13333:             }
                   13334:             if (ref($hashref) eq 'HASH') {
                   13335:                 %{$hashref} = (
                   13336:                                 sums     => \%chksum,
                   13337:                                 versions => \%revnum,
                   13338:                               );
                   13339:             }
                   13340:         }
                   13341:     }
1.869     albertel 13342:     return;
1.852     albertel 13343: }
1.1172.2.17  raeburn  13344: 
                   13345: sub fetch_dns_checksums {
                   13346:     my %checksums;
1.1172.2.34  raeburn  13347:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13348:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13349:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13350:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13351:              \%checksums);
                   13352:     return \%checksums;
                   13353: }
                   13354: 
1.327     albertel 13355: # ------------------------------------------------------------ Read domain file
                   13356: {
1.852     albertel 13357:     my $loaded;
1.846     albertel 13358:     my %domain;
                   13359: 
1.852     albertel 13360:     sub parse_domain_tab {
                   13361: 	my ($lines) = @_;
                   13362: 	foreach my $line (@$lines) {
                   13363: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13364: 
1.846     albertel 13365: 	    chomp($line);
1.852     albertel 13366: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13367: 	    my %this_domain;
                   13368: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13369: 			       'lang_def', 'city', 'longi', 'lati',
                   13370: 			       'primary') {
                   13371: 		$this_domain{$field} = shift(@elements);
                   13372: 	    }
                   13373: 	    $domain{$name} = \%this_domain;
1.852     albertel 13374: 	}
                   13375:     }
1.864     albertel 13376: 
                   13377:     sub reset_domain_info {
                   13378: 	undef($loaded);
                   13379: 	undef(%domain);
                   13380:     }
                   13381: 
1.852     albertel 13382:     sub load_domain_tab {
1.1172.2.70  raeburn  13383: 	my ($ignore_cache,$nocache) = @_;
                   13384: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13385: 	my $fh;
1.1172.2.96  raeburn  13386: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13387: 	    my @lines = <$fh>;
                   13388: 	    &parse_domain_tab(\@lines);
1.448     albertel 13389: 	}
1.852     albertel 13390: 	close($fh);
                   13391: 	$loaded = 1;
1.327     albertel 13392:     }
1.846     albertel 13393: 
                   13394:     sub domain {
1.852     albertel 13395: 	&load_domain_tab() if (!$loaded);
                   13396: 
1.846     albertel 13397: 	my ($name,$what) = @_;
                   13398: 	return if ( !exists($domain{$name}) );
                   13399: 
                   13400: 	if (!$what) {
                   13401: 	    return $domain{$name}{'description'};
                   13402: 	}
                   13403: 	return $domain{$name}{$what};
                   13404:     }
1.974     raeburn  13405: 
                   13406:     sub domain_info {
                   13407:         &load_domain_tab() if (!$loaded);
                   13408:         return %domain;
                   13409:     }
                   13410: 
1.327     albertel 13411: }
                   13412: 
                   13413: 
1.1       albertel 13414: # ------------------------------------------------------------- Read hosts file
                   13415: {
1.838     albertel 13416:     my %hostname;
1.844     albertel 13417:     my %hostdom;
1.845     albertel 13418:     my %libserv;
1.852     albertel 13419:     my $loaded;
1.888     albertel 13420:     my %name_to_host;
1.1074    raeburn  13421:     my %internetdom;
1.1107    raeburn  13422:     my %LC_dns_serv;
1.852     albertel 13423: 
                   13424:     sub parse_hosts_tab {
                   13425: 	my ($file) = @_;
                   13426: 	foreach my $configline (@$file) {
                   13427: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13428:             chomp($configline);
                   13429: 	    if ($configline =~ /^\^/) {
                   13430:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13431:                     $LC_dns_serv{$1} = 1;
                   13432:                 }
                   13433:                 next;
                   13434:             }
1.1074    raeburn  13435: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13436: 	    $name=~s/\s//g;
                   13437: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13438:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13439:                     my $curr = $hostname{$id};
                   13440:                     my $skip;
                   13441:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13442:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13443:                             $skip = 1;
                   13444:                         } else {
                   13445:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13446:                         }
                   13447:                     }
                   13448:                     unless ($skip) {
                   13449:                         push(@{$name_to_host{$name}},$id);
                   13450:                     }
                   13451:                 } else {
                   13452:                     push(@{$name_to_host{$name}},$id);
                   13453:                 }
1.852     albertel 13454: 		$hostname{$id}=$name;
                   13455: 		$hostdom{$id}=$domain;
                   13456: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13457:                 if (defined($protocol)) {
                   13458:                     if ($protocol eq 'https') {
                   13459:                         $protocol{$id} = $protocol;
                   13460:                     } else {
                   13461:                         $protocol{$id} = 'http'; 
                   13462:                     }
1.968     raeburn  13463:                 } else {
1.969     raeburn  13464:                     $protocol{$id} = 'http';
1.968     raeburn  13465:                 }
1.1074    raeburn  13466:                 if (defined($intdom)) {
                   13467:                     $internetdom{$id} = $intdom;
                   13468:                 }
1.852     albertel 13469: 	    }
                   13470: 	}
                   13471:     }
1.864     albertel 13472:     
                   13473:     sub reset_hosts_info {
1.897     albertel 13474: 	&purge_remembered();
1.864     albertel 13475: 	&reset_domain_info();
                   13476: 	&reset_hosts_ip_info();
1.892     albertel 13477: 	undef(%name_to_host);
1.864     albertel 13478: 	undef(%hostname);
                   13479: 	undef(%hostdom);
                   13480: 	undef(%libserv);
                   13481: 	undef($loaded);
                   13482:     }
1.1       albertel 13483: 
1.852     albertel 13484:     sub load_hosts_tab {
1.1172.2.70  raeburn  13485: 	my ($ignore_cache,$nocache) = @_;
                   13486: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13487: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13488: 	my @config = <$config>;
                   13489: 	&parse_hosts_tab(\@config);
                   13490: 	close($config);
                   13491: 	$loaded=1;
1.1       albertel 13492:     }
1.852     albertel 13493: 
1.838     albertel 13494:     sub hostname {
1.852     albertel 13495: 	&load_hosts_tab() if (!$loaded);
                   13496: 
1.838     albertel 13497: 	my ($lonid) = @_;
                   13498: 	return $hostname{$lonid};
                   13499:     }
1.845     albertel 13500: 
1.838     albertel 13501:     sub all_hostnames {
1.852     albertel 13502: 	&load_hosts_tab() if (!$loaded);
                   13503: 
1.838     albertel 13504: 	return %hostname;
                   13505:     }
1.845     albertel 13506: 
1.888     albertel 13507:     sub all_names {
1.1172.2.70  raeburn  13508:         my ($ignore_cache,$nocache) = @_;
                   13509: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13510: 
                   13511: 	return %name_to_host;
                   13512:     }
                   13513: 
1.974     raeburn  13514:     sub all_host_domain {
                   13515:         &load_hosts_tab() if (!$loaded);
                   13516:         return %hostdom;
                   13517:     }
                   13518: 
1.845     albertel 13519:     sub is_library {
1.852     albertel 13520: 	&load_hosts_tab() if (!$loaded);
                   13521: 
1.845     albertel 13522: 	return exists($libserv{$_[0]});
                   13523:     }
                   13524: 
                   13525:     sub all_library {
1.852     albertel 13526: 	&load_hosts_tab() if (!$loaded);
                   13527: 
1.845     albertel 13528: 	return %libserv;
                   13529:     }
                   13530: 
1.1062    droeschl 13531:     sub unique_library {
                   13532: 	#2x reverse removes all hostnames that appear more than once
                   13533:         my %unique = reverse &all_library();
                   13534:         return reverse %unique;
                   13535:     }
                   13536: 
1.841     albertel 13537:     sub get_servers {
1.852     albertel 13538: 	&load_hosts_tab() if (!$loaded);
                   13539: 
1.841     albertel 13540: 	my ($domain,$type) = @_;
                   13541: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13542: 	                                          : %hostname;
                   13543: 	my %result;
1.842     albertel 13544: 	if (ref($domain) eq 'ARRAY') {
                   13545: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13546: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13547: 		    $result{$host} = $hostname;
                   13548: 		}
                   13549: 	    }
                   13550: 	} else {
                   13551: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13552: 		if ($hostdom{$host} eq $domain) {
                   13553: 		    $result{$host} = $hostname;
                   13554: 		}
1.841     albertel 13555: 	    }
                   13556: 	}
                   13557: 	return %result;
                   13558:     }
1.845     albertel 13559: 
1.1062    droeschl 13560:     sub get_unique_servers {
                   13561:         my %unique = reverse &get_servers(@_);
                   13562: 	return reverse %unique;
                   13563:     }
                   13564: 
1.844     albertel 13565:     sub host_domain {
1.852     albertel 13566: 	&load_hosts_tab() if (!$loaded);
                   13567: 
1.844     albertel 13568: 	my ($lonid) = @_;
                   13569: 	return $hostdom{$lonid};
                   13570:     }
                   13571: 
1.841     albertel 13572:     sub all_domains {
1.852     albertel 13573: 	&load_hosts_tab() if (!$loaded);
                   13574: 
1.841     albertel 13575: 	my %seen;
                   13576: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13577: 	return @uniq;
                   13578:     }
1.1074    raeburn  13579: 
                   13580:     sub internet_dom {
                   13581:         &load_hosts_tab() if (!$loaded);
                   13582: 
                   13583:         my ($lonid) = @_;
                   13584:         return $internetdom{$lonid};
                   13585:     }
1.1107    raeburn  13586: 
                   13587:     sub is_LC_dns {
                   13588:         &load_hosts_tab() if (!$loaded);
                   13589: 
                   13590:         my ($hostname) = @_;
                   13591:         return exists($LC_dns_serv{$hostname});
                   13592:     }
                   13593: 
1.1       albertel 13594: }
                   13595: 
1.847     albertel 13596: { 
                   13597:     my %iphost;
1.856     albertel 13598:     my %name_to_ip;
                   13599:     my %lonid_to_ip;
1.869     albertel 13600: 
1.847     albertel 13601:     sub get_hosts_from_ip {
                   13602: 	my ($ip) = @_;
                   13603: 	my %iphosts = &get_iphost();
                   13604: 	if (ref($iphosts{$ip})) {
                   13605: 	    return @{$iphosts{$ip}};
                   13606: 	}
                   13607: 	return;
1.839     albertel 13608:     }
1.864     albertel 13609:     
                   13610:     sub reset_hosts_ip_info {
                   13611: 	undef(%iphost);
                   13612: 	undef(%name_to_ip);
                   13613: 	undef(%lonid_to_ip);
                   13614:     }
1.856     albertel 13615: 
                   13616:     sub get_host_ip {
                   13617: 	my ($lonid) = @_;
                   13618: 	if (exists($lonid_to_ip{$lonid})) {
                   13619: 	    return $lonid_to_ip{$lonid};
                   13620: 	}
                   13621: 	my $name=&hostname($lonid);
                   13622:    	my $ip = gethostbyname($name);
                   13623: 	return if (!$ip || length($ip) ne 4);
                   13624: 	$ip=inet_ntoa($ip);
                   13625: 	$name_to_ip{$name}   = $ip;
                   13626: 	$lonid_to_ip{$lonid} = $ip;
                   13627: 	return $ip;
                   13628:     }
1.847     albertel 13629:     
                   13630:     sub get_iphost {
1.1172.2.70  raeburn  13631: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13632: 
1.869     albertel 13633: 	if (!$ignore_cache) {
                   13634: 	    if (%iphost) {
                   13635: 		return %iphost;
                   13636: 	    }
                   13637: 	    my ($ip_info,$cached)=
                   13638: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13639: 	    if ($cached) {
                   13640: 		%iphost      = %{$ip_info->[0]};
                   13641: 		%name_to_ip  = %{$ip_info->[1]};
                   13642: 		%lonid_to_ip = %{$ip_info->[2]};
                   13643: 		return %iphost;
                   13644: 	    }
                   13645: 	}
1.894     albertel 13646: 
                   13647: 	# get yesterday's info for fallback
                   13648: 	my %old_name_to_ip;
                   13649: 	my ($ip_info,$cached)=
                   13650: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13651: 	if ($cached) {
                   13652: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13653: 	}
                   13654: 
1.1172.2.70  raeburn  13655: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13656: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13657: 	    my $ip;
                   13658: 	    if (!exists($name_to_ip{$name})) {
                   13659: 		$ip = gethostbyname($name);
                   13660: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13661: 		    if (defined($old_name_to_ip{$name})) {
                   13662: 			$ip = $old_name_to_ip{$name};
                   13663: 			&logthis("Can't find $name defaulting to old $ip");
                   13664: 		    } else {
                   13665: 			&logthis("Name $name no IP found");
                   13666: 			next;
                   13667: 		    }
                   13668: 		} else {
                   13669: 		    $ip=inet_ntoa($ip);
1.847     albertel 13670: 		}
                   13671: 		$name_to_ip{$name} = $ip;
                   13672: 	    } else {
                   13673: 		$ip = $name_to_ip{$name};
1.653     albertel 13674: 	    }
1.888     albertel 13675: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13676: 		$lonid_to_ip{$id} = $ip;
                   13677: 	    }
                   13678: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13679: 	}
1.1172.2.70  raeburn  13680:         unless ($nocache) {
                   13681: 	    &do_cache_new('iphost','iphost',
                   13682: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13683: 		          48*60*60);
                   13684:         }
1.869     albertel 13685: 
1.847     albertel 13686: 	return %iphost;
1.598     albertel 13687:     }
                   13688: 
1.992     raeburn  13689:     #
                   13690:     #  Given a DNS returns the loncapa host name for that DNS 
                   13691:     # 
                   13692:     sub host_from_dns {
                   13693:         my ($dns) = @_;
                   13694:         my @hosts;
                   13695:         my $ip;
                   13696: 
1.993     raeburn  13697:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13698:             $ip = $name_to_ip{$dns};
                   13699:         }
                   13700:         if (!$ip) {
                   13701:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13702:             if (length($ip) == 4) { 
                   13703: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13704:             }
                   13705:         }
                   13706:         if ($ip) {
                   13707: 	    @hosts = get_hosts_from_ip($ip);
                   13708: 	    return $hosts[0];
                   13709:         }
                   13710:         return undef;
1.986     foxr     13711:     }
1.992     raeburn  13712: 
1.1074    raeburn  13713:     sub get_internet_names {
                   13714:         my ($lonid) = @_;
                   13715:         return if ($lonid eq '');
                   13716:         my ($idnref,$cached)=
                   13717:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13718:         if ($cached) {
                   13719:             return $idnref;
                   13720:         }
                   13721:         my $ip = &get_host_ip($lonid);
                   13722:         my @hosts = &get_hosts_from_ip($ip);
                   13723:         my %iphost = &get_iphost();
                   13724:         my (@idns,%seen);
                   13725:         foreach my $id (@hosts) {
                   13726:             my $dom = &host_domain($id);
                   13727:             my $prim_id = &domain($dom,'primary');
                   13728:             my $prim_ip = &get_host_ip($prim_id);
                   13729:             next if ($seen{$prim_ip});
                   13730:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13731:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13732:                     my $intdom = &internet_dom($id);
                   13733:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13734:                         push(@idns,$intdom);
                   13735:                     }
                   13736:                 }
                   13737:             }
                   13738:             $seen{$prim_ip} = 1;
                   13739:         }
1.1172.2.23  raeburn  13740:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13741:     }
                   13742: 
1.986     foxr     13743: }
                   13744: 
1.1079    raeburn  13745: sub all_loncaparevs {
1.1172.2.39  raeburn  13746:     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  13747: }
                   13748: 
1.1172.2.27  raeburn  13749: # ------------------------------------------------------- Read loncaparev table
                   13750: {
                   13751:     sub load_loncaparevs {
                   13752:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13753:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13754:                 while (my $configline=<$config>) {
                   13755:                     chomp($configline);
                   13756:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13757:                     $loncaparevs{$hostid}=$loncaparev;
                   13758:                 }
                   13759:                 close($config);
                   13760:             }
                   13761:         }
                   13762:     }
                   13763: }
                   13764: 
                   13765: # ----------------------------------------------------- Read serverhostID table
                   13766: {
                   13767:     sub load_serverhomeIDs {
                   13768:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13769:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13770:                 while (my $configline=<$config>) {
                   13771:                     chomp($configline);
                   13772:                     my ($name,$id)=split(/:/,$configline);
                   13773:                     $serverhomeIDs{$name}=$id;
                   13774:                 }
                   13775:                 close($config);
                   13776:             }
                   13777:         }
                   13778:     }
                   13779: }
                   13780: 
                   13781: 
1.862     albertel 13782: BEGIN {
                   13783: 
                   13784: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13785:     unless ($readit) {
                   13786: {
                   13787:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13788:     %perlvar = (%perlvar,%{$configvars});
                   13789: }
                   13790: 
                   13791: 
1.1       albertel 13792: # ------------------------------------------------------ Read spare server file
                   13793: {
1.1172.2.96  raeburn  13794:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13795: 
                   13796:     while (my $configline=<$config>) {
                   13797:        chomp($configline);
1.284     matthew  13798:        if ($configline) {
1.784     albertel 13799: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13800: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13801: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13802:        }
                   13803:     }
1.448     albertel 13804:     close($config);
1.1       albertel 13805: }
1.11      www      13806: # ------------------------------------------------------------ Read permissions
                   13807: {
1.1172.2.96  raeburn  13808:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13809: 
                   13810:     while (my $configline=<$config>) {
1.448     albertel 13811: 	chomp($configline);
                   13812: 	if ($configline) {
                   13813: 	    my ($role,$perm)=split(/ /,$configline);
                   13814: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13815: 	}
1.11      www      13816:     }
1.448     albertel 13817:     close($config);
1.11      www      13818: }
                   13819: 
                   13820: # -------------------------------------------- Read plain texts for permissions
                   13821: {
1.1172.2.96  raeburn  13822:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13823: 
                   13824:     while (my $configline=<$config>) {
1.448     albertel 13825: 	chomp($configline);
                   13826: 	if ($configline) {
1.742     raeburn  13827: 	    my ($short,@plain)=split(/:/,$configline);
                   13828:             %{$prp{$short}} = ();
                   13829: 	    if (@plain > 0) {
                   13830:                 $prp{$short}{'std'} = $plain[0];
                   13831:                 for (my $i=1; $i<@plain; $i++) {
                   13832:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13833:                 }
                   13834:             }
1.448     albertel 13835: 	}
1.135     www      13836:     }
1.448     albertel 13837:     close($config);
1.135     www      13838: }
                   13839: 
                   13840: # ---------------------------------------------------------- Read package table
                   13841: {
1.1172.2.96  raeburn  13842:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13843: 
                   13844:     while (my $configline=<$config>) {
1.483     albertel 13845: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13846: 	chomp($configline);
                   13847: 	my ($short,$plain)=split(/:/,$configline);
                   13848: 	my ($pack,$name)=split(/\&/,$short);
                   13849: 	if ($plain ne '') {
                   13850: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13851: 	    $packagetab{$short}=$plain; 
                   13852: 	}
1.11      www      13853:     }
1.448     albertel 13854:     close($config);
1.329     matthew  13855: }
                   13856: 
1.1172.2.27  raeburn  13857: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13858: 
1.1172.2.27  raeburn  13859: &load_loncaparevs();
                   13860: 
                   13861: # ------------------------------------------------------- Read serverhostID table
                   13862: 
                   13863: &load_serverhomeIDs();
1.1074    raeburn  13864: 
1.1172.2.27  raeburn  13865: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13866: {
                   13867:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13868:     if (-e $file) {
                   13869:         my $parser = HTML::LCParser->new($file);
                   13870:         while (my $token = $parser->get_token()) {
                   13871:             if ($token->[0] eq 'S') {
                   13872:                 my $item = $token->[1];
                   13873:                 my $name = $token->[2]{'name'};
                   13874:                 my $value = $token->[2]{'value'};
                   13875:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13876:                     my $release = $parser->get_text();
                   13877:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13878:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13879:                 }
                   13880:             }
                   13881:         }
                   13882:     }
1.1073    raeburn  13883: }
                   13884: 
1.1138    raeburn  13885: # ---------------------------------------------------------- Read managers table
                   13886: {
                   13887:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13888:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13889:             while (my $configline=<$config>) {
                   13890:                 chomp($configline);
                   13891:                 next if ($configline =~ /^\#/);
                   13892:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13893:                     $managerstab{$configline} = 1;
                   13894:                 }
                   13895:             }
                   13896:             close($config);
                   13897:         }
                   13898:     }
                   13899: }
                   13900: 
1.329     matthew  13901: # ------------- set up temporary directory
                   13902: {
1.1117    foxr     13903:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13904: 
1.11      www      13905: }
                   13906: 
1.1172.2.104  raeburn  13907: # ------------- set default texengine (domain default overrides this)
                   13908: {
                   13909:     $deftex = LONCAPA::texengine();
                   13910: }
                   13911: 
1.794     albertel 13912: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13913: 				'compress_threshold'=> 20_000,
                   13914:  			        });
1.185     www      13915: 
1.281     www      13916: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13917: $dumpcount=0;
1.958     www      13918: $locknum=0;
1.22      www      13919: 
1.163     harris41 13920: &logtouch();
1.672     albertel 13921: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13922: $readit=1;
1.564     albertel 13923:     {
                   13924: 	use integer;
                   13925: 	my $test=(2**32)+1;
1.568     albertel 13926: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13927: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13928:     }
1.195     www      13929: }
1.1       albertel 13930: }
1.179     www      13931: 
1.1       albertel 13932: 1;
1.191     harris41 13933: __END__
                   13934: 
1.243     albertel 13935: =pod
                   13936: 
1.191     harris41 13937: =head1 NAME
                   13938: 
1.243     albertel 13939: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13940: 
                   13941: =head1 SYNOPSIS
                   13942: 
1.243     albertel 13943: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13944: 
                   13945:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13946: 
1.243     albertel 13947: Common parameters:
                   13948: 
                   13949: =over 4
                   13950: 
                   13951: =item *
                   13952: 
                   13953: $uname : an internal username (if $cname expecting a course Id specifically)
                   13954: 
                   13955: =item *
                   13956: 
                   13957: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13958: 
                   13959: =item *
                   13960: 
                   13961: $symb : a resource instance identifier
                   13962: 
                   13963: =item *
                   13964: 
                   13965: $namespace : the name of a .db file that contains the data needed or
                   13966: being set.
                   13967: 
                   13968: =back
                   13969: 
1.394     bowersj2 13970: =head1 OVERVIEW
1.191     harris41 13971: 
1.394     bowersj2 13972: lonnet provides subroutines which interact with the
                   13973: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13974: about classes, users, and resources.
1.243     albertel 13975: 
                   13976: For many of these objects you can also use this to store data about
                   13977: them or modify them in various ways.
1.191     harris41 13978: 
1.394     bowersj2 13979: =head2 Symbs
1.191     harris41 13980: 
1.394     bowersj2 13981: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13982: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13983: map, the resource number of the resource in the map, and the URL of
                   13984: the resource itself. The latter is somewhat redundant, but might help
                   13985: if maps change.
                   13986: 
                   13987: An example is
                   13988: 
                   13989:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13990: 
                   13991: The respective map entry is
                   13992: 
                   13993:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13994:   title="Problem 2">
                   13995:  </resource>
                   13996: 
                   13997: Symbs are used by the random number generator, as well as to store and
                   13998: restore data specific to a certain instance of for example a problem.
                   13999: 
                   14000: =head2 Storing And Retrieving Data
                   14001: 
                   14002: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14003: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14004: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14005: is is the non-critical message twin of cstore. These functions are for
                   14006: handlers to store a perl hash to a user's permanent data space in an
                   14007: easy manner, and to retrieve it again on another call. It is expected
                   14008: that a handler would use this once at the beginning to retrieve data,
                   14009: and then again once at the end to send only the new data back.
                   14010: 
                   14011: The data is stored in the user's data directory on the user's
                   14012: homeserver under the ID of the course.
                   14013: 
                   14014: The hash that is returned by restore will have all of the previous
                   14015: value for all of the elements of the hash.
                   14016: 
                   14017: Example:
                   14018: 
                   14019:  #creating a hash
                   14020:  my %hash;
                   14021:  $hash{'foo'}='bar';
                   14022: 
                   14023:  #storing it
                   14024:  &Apache::lonnet::cstore(\%hash);
                   14025: 
                   14026:  #changing a value
                   14027:  $hash{'foo'}='notbar';
                   14028: 
                   14029:  #adding a new value
                   14030:  $hash{'bar'}='foo';
                   14031:  &Apache::lonnet::cstore(\%hash);
                   14032: 
                   14033:  #retrieving the hash
                   14034:  my %history=&Apache::lonnet::restore();
                   14035: 
                   14036:  #print the hash
                   14037:  foreach my $key (sort(keys(%history))) {
                   14038:    print("\%history{$key} = $history{$key}");
                   14039:  }
                   14040: 
                   14041: Will print out:
1.191     harris41 14042: 
1.394     bowersj2 14043:  %history{1:foo} = bar
                   14044:  %history{1:keys} = foo:timestamp
                   14045:  %history{1:timestamp} = 990455579
                   14046:  %history{2:bar} = foo
                   14047:  %history{2:foo} = notbar
                   14048:  %history{2:keys} = foo:bar:timestamp
                   14049:  %history{2:timestamp} = 990455580
                   14050:  %history{bar} = foo
                   14051:  %history{foo} = notbar
                   14052:  %history{timestamp} = 990455580
                   14053:  %history{version} = 2
                   14054: 
                   14055: Note that the special hash entries C<keys>, C<version> and
                   14056: C<timestamp> were added to the hash. C<version> will be equal to the
                   14057: total number of versions of the data that have been stored. The
                   14058: C<timestamp> attribute will be the UNIX time the hash was
                   14059: stored. C<keys> is available in every historical section to list which
                   14060: keys were added or changed at a specific historical revision of a
                   14061: hash.
                   14062: 
                   14063: B<Warning>: do not store the hash that restore returns directly. This
                   14064: will cause a mess since it will restore the historical keys as if the
                   14065: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14066: 
1.394     bowersj2 14067: Calling convention:
1.191     harris41 14068: 
1.1172.2.27  raeburn  14069:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14070:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14071: 
1.394     bowersj2 14072: For more detailed information, see lonnet specific documentation.
1.191     harris41 14073: 
1.394     bowersj2 14074: =head1 RETURN MESSAGES
1.191     harris41 14075: 
1.394     bowersj2 14076: =over 4
1.191     harris41 14077: 
1.394     bowersj2 14078: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14079: 
1.394     bowersj2 14080: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14081: when the connection is brought back up
1.191     harris41 14082: 
1.394     bowersj2 14083: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14084: for later delivery
1.191     harris41 14085: 
1.967     bisitz   14086: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14087: 
1.394     bowersj2 14088: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14089: that was requested
1.191     harris41 14090: 
1.243     albertel 14091: =back
1.191     harris41 14092: 
1.243     albertel 14093: =head1 PUBLIC SUBROUTINES
1.191     harris41 14094: 
1.243     albertel 14095: =head2 Session Environment Functions
1.191     harris41 14096: 
1.243     albertel 14097: =over 4
1.191     harris41 14098: 
1.394     bowersj2 14099: =item * 
                   14100: X<appenv()>
1.949     raeburn  14101: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14102: the user envirnoment file, and will be restored for each access this
1.620     albertel 14103: user makes during this session, also modifies the %env for the current
1.949     raeburn  14104: process. Optional rolesarrayref - if defined contains a reference to an array
                   14105: of roles which are exempt from the restriction on modifying user.role entries 
                   14106: in the user's environment.db and in %env.    
1.191     harris41 14107: 
                   14108: =item *
1.394     bowersj2 14109: X<delenv()>
1.987     raeburn  14110: B<delenv($delthis,$regexp)>: removes all items from the session
                   14111: environment file that begin with $delthis. If the 
                   14112: optional second arg - $regexp - is true, $delthis is treated as a 
                   14113: regular expression, otherwise \Q$delthis\E is used. 
                   14114: The values are also deleted from the current processes %env.
1.191     harris41 14115: 
1.795     albertel 14116: =item * get_env_multiple($name) 
                   14117: 
                   14118: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14119: values may be defined and end up as an array ref.
                   14120: 
                   14121: returns an array of values
                   14122: 
1.243     albertel 14123: =back
                   14124: 
                   14125: =head2 User Information
1.191     harris41 14126: 
1.243     albertel 14127: =over 4
1.191     harris41 14128: 
                   14129: =item *
1.394     bowersj2 14130: X<queryauthenticate()>
                   14131: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14132: authentication scheme
                   14133: 
                   14134: =item *
1.394     bowersj2 14135: X<authenticate()>
1.1073    raeburn  14136: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14137: authenticate user from domain's lib servers (first use the current
                   14138: one). C<$upass> should be the users password.
1.1073    raeburn  14139: $checkdefauth is optional (value is 1 if a check should be made to
                   14140:    authenticate user using default authentication method, and allow
                   14141:    account creation if username does not have account in the domain).
                   14142: $clientcancheckhost is optional (value is 1 if checking whether the
                   14143:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14144: 
                   14145: =item *
1.394     bowersj2 14146: X<homeserver()>
                   14147: B<homeserver($uname,$udom)>: find the server which has
                   14148: the user's directory and files (there must be only one), this caches
                   14149: the answer, and also caches if there is a borken connection.
1.191     harris41 14150: 
                   14151: =item *
1.394     bowersj2 14152: X<idget()>
                   14153: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14154: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14155: username, and only 1 username per ID in a specific domain) (returns
                   14156: hash: id=>name,id=>name)
1.191     harris41 14157: 
                   14158: =item *
1.394     bowersj2 14159: X<idrget()>
                   14160: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14161: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14162: 
                   14163: =item *
1.394     bowersj2 14164: X<idput()>
                   14165: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14166: 
                   14167: =item *
1.394     bowersj2 14168: X<rolesinit()>
1.1169    droeschl 14169: B<rolesinit($udom,$username)>: get user privileges.
                   14170: returns user role, first access and timer interval hashes
1.243     albertel 14171: 
                   14172: =item *
1.1171    droeschl 14173: X<privileged()>
                   14174: B<privileged($username,$domain)>: returns a true if user has a
                   14175: privileged and active role (i.e. su or dc), false otherwise.
                   14176: 
                   14177: =item *
1.551     albertel 14178: X<getsection()>
                   14179: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14180: course $cname, return section name/number or '' for "not in course"
                   14181: and '-1' for "no section"
                   14182: 
                   14183: =item *
1.394     bowersj2 14184: X<userenvironment()>
                   14185: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14186: passed in @what from the requested user's environment, returns a hash
                   14187: 
1.858     raeburn  14188: =item * 
                   14189: X<userlog_query()>
1.859     albertel 14190: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14191: activity.log file. %filters defines filters applied when parsing the
                   14192: log file. These can be start or end timestamps, or the type of action
                   14193: - log to look for Login or Logout events, check for Checkin or
                   14194: Checkout, role for role selection. The response is in the form
                   14195: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14196: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14197: 
1.243     albertel 14198: =back
                   14199: 
                   14200: =head2 User Roles
                   14201: 
                   14202: =over 4
                   14203: 
                   14204: =item *
                   14205: 
1.1172.2.65  raeburn  14206: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14207: returns codes for allowed actions.
                   14208: 
                   14209: The first argument is required, all others are optional.
                   14210: 
                   14211: $priv is the privilege being checked.
                   14212: $uri contains additional information about what is being checked for access (e.g.,
                   14213: URL, course ID etc.).
                   14214: $symb is the unique resource instance identifier in a course; if needed,
                   14215: but not provided, it will be retrieved via a call to &symbread().
                   14216: $role is the role for which a priv is being checked (only used if priv is evb).
                   14217: $clientip is the user's IP address (only used when checking for access to portfolio
                   14218: files).
                   14219: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14220: prevents recursive calls to &allowed.
                   14221: 
1.243     albertel 14222:  F: full access
                   14223:  U,I,K: authentication modes (cxx only)
                   14224:  '': forbidden
                   14225:  1: user needs to choose course
                   14226:  2: browse allowed
1.766     albertel 14227:  A: passphrase authentication needed
1.1172.2.65  raeburn  14228:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14229: 
                   14230: =item *
                   14231: 
1.1172.2.13  raeburn  14232: constructaccess($url,$setpriv) : check for access to construction space URL
                   14233: 
                   14234: See if the owner domain and name in the URL match those in the
                   14235: expected environment.  If so, return three element list
                   14236: ($ownername,$ownerdomain,$ownerhome).
                   14237: 
                   14238: Otherwise return the null string.
                   14239: 
                   14240: If second argument 'setpriv' is true, it assigns the privileges,
                   14241: and returns the same three element list, unless the owner has
                   14242: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14243: in which case the null string is returned.
                   14244: 
                   14245: =item *
                   14246: 
1.1172.2.84  raeburn  14247: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14248: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14249: for system, domain, and course level. $uname and $udom are optional (current
                   14250: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14251: 
                   14252: =item *
                   14253: 
1.988     raeburn  14254: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14255: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14256: $type is Course (default) or Community.
1.988     raeburn  14257: If $forcedefault evaluates to true, text returned will be default 
                   14258: text for $type. Otherwise, if this is a course, the text returned 
                   14259: will be a custom name for the role (if defined in the course's 
                   14260: environment).  If no custom name is defined the default is returned.
                   14261:    
1.832     raeburn  14262: =item *
                   14263: 
1.1172.2.23  raeburn  14264: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14265: All arguments are optional. Returns a hash of a roles, either for
                   14266: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14267: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14268: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14269: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14270: For each key, value is set to colon-separated start and end times for
                   14271: the role.  If no username and domain are specified, will default to
1.934     raeburn  14272: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14273: of role statuses (active, future or previous), roles 
                   14274: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14275: to restrict the list of roles reported. If no array ref is 
                   14276: provided for types, will default to return only active roles.
1.834     albertel 14277: 
1.1172.2.13  raeburn  14278: =item *
                   14279: 
                   14280: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14281: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14282: 
                   14283: Additional optional arguments are: $type (if role checking is to be restricted
                   14284: to certain user status types -- previous (expired roles), active (currently
                   14285: available roles) or future (roles available in the future), and
                   14286: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14287: have active Domain Coordinator role in course's domain or in additional
                   14288: domains (specified in 'Domains to check for privileged users' in course
                   14289: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14290: 
                   14291: =item *
                   14292: 
                   14293: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14294: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14295: $possdomains and $possroles are optional array refs -- to domains to check and
                   14296: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14297: users' roles.db to check for a dc or su role in any domain. This can be
                   14298: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14299: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14300: this then allows &privileged_by_domain() to be used, which caches the identity
                   14301: of privileged users, eliminating the need for repeated calls to &dump().
                   14302: 
                   14303: =item *
                   14304: 
                   14305: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14306: where the outer hash keys are domains specified in the $possdomains array ref,
                   14307: next inner hash keys are privileged roles specified in the $roles array ref,
                   14308: and the innermost hash contains key = value pairs for username:domain = end:start
                   14309: for active or future "privileged" users with that role in that domain. To avoid
                   14310: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14311: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14312: 
1.243     albertel 14313: =back
                   14314: 
                   14315: =head2 User Modification
                   14316: 
                   14317: =over 4
                   14318: 
                   14319: =item *
                   14320: 
1.957     raeburn  14321: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14322: user for the level given by URL.  Optional start and end dates (leave empty
                   14323: string or zero for "no date")
1.191     harris41 14324: 
                   14325: =item *
                   14326: 
1.243     albertel 14327: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14328: change a users, password, possible return values are: ok,
                   14329: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14330: refused
1.191     harris41 14331: 
                   14332: =item *
                   14333: 
1.243     albertel 14334: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14335: 
                   14336: =item *
                   14337: 
1.1058    raeburn  14338: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14339:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14340: 
                   14341: will update user information (firstname,middlename,lastname,generation,
                   14342: permanentemail), and if forceid is true, student/employee ID also.
                   14343: A user's institutional affiliation(s) can also be updated.
                   14344: User information fields will not be overwritten with empty entries 
                   14345: unless the field is included in the $candelete array reference.
                   14346: This array is included when a single user is modified via "Manage Users",
                   14347: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14348: 
                   14349: =item *
                   14350: 
1.286     matthew  14351: modifystudent
                   14352: 
1.957     raeburn  14353: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14354: The course id is resolved based on the current user's environment.  
                   14355: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14356: associated with a course.
                   14357: 
1.297     matthew  14358: This call is essentially a wrapper for lonnet::modifyuser and
                   14359: lonnet::modify_student_enrollment
1.286     matthew  14360: 
                   14361: Inputs: 
                   14362: 
                   14363: =over 4
                   14364: 
1.957     raeburn  14365: =item B<$udom> Student's loncapa domain
1.286     matthew  14366: 
1.957     raeburn  14367: =item B<$uname> Student's loncapa login name
1.286     matthew  14368: 
1.964     bisitz   14369: =item B<$uid> Student/Employee ID
1.286     matthew  14370: 
1.957     raeburn  14371: =item B<$umode> Student's authentication mode
1.286     matthew  14372: 
1.957     raeburn  14373: =item B<$upass> Student's password
1.286     matthew  14374: 
1.957     raeburn  14375: =item B<$first> Student's first name
1.286     matthew  14376: 
1.957     raeburn  14377: =item B<$middle> Student's middle name
1.286     matthew  14378: 
1.957     raeburn  14379: =item B<$last> Student's last name
1.286     matthew  14380: 
1.957     raeburn  14381: =item B<$gene> Student's generation
1.286     matthew  14382: 
1.957     raeburn  14383: =item B<$usec> Student's section in course
1.286     matthew  14384: 
                   14385: =item B<$end> Unix time of the roles expiration
                   14386: 
                   14387: =item B<$start> Unix time of the roles start date
                   14388: 
                   14389: =item B<$forceid> If defined, allow $uid to be changed
                   14390: 
                   14391: =item B<$desiredhome> server to use as home server for student
                   14392: 
1.957     raeburn  14393: =item B<$email> Student's permanent e-mail address
                   14394: 
                   14395: =item B<$type> Type of enrollment (auto or manual)
                   14396: 
1.963     raeburn  14397: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14398: 
                   14399: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14400: 
1.963     raeburn  14401: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14402: 
1.963     raeburn  14403: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14404: 
1.1172.2.19  raeburn  14405: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14406: 
                   14407: =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  14408: 
1.286     matthew  14409: =back
1.297     matthew  14410: 
                   14411: =item *
                   14412: 
                   14413: modify_student_enrollment
                   14414: 
1.1172.2.31  raeburn  14415: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14416: 'role.request.course' must be defined for this function to proceed.
                   14417: 
                   14418: Inputs:
                   14419: 
                   14420: =over 4
                   14421: 
1.1172.2.31  raeburn  14422: =item $udom, student's domain
1.297     matthew  14423: 
1.1172.2.31  raeburn  14424: =item $uname, student's name
1.297     matthew  14425: 
1.1172.2.31  raeburn  14426: =item $uid, student's user id
1.297     matthew  14427: 
1.1172.2.31  raeburn  14428: =item $first, student's first name
1.297     matthew  14429: 
                   14430: =item $middle
                   14431: 
                   14432: =item $last
                   14433: 
                   14434: =item $gene
                   14435: 
                   14436: =item $usec
                   14437: 
                   14438: =item $end
                   14439: 
                   14440: =item $start
                   14441: 
1.957     raeburn  14442: =item $type
                   14443: 
                   14444: =item $locktype
                   14445: 
                   14446: =item $cid
                   14447: 
                   14448: =item $selfenroll
                   14449: 
                   14450: =item $context
                   14451: 
1.1172.2.19  raeburn  14452: =item $credits, number of credits student will earn from this class
                   14453: 
1.1172.2.76  raeburn  14454: =item $instsec, institutional course section code for student
                   14455: 
1.297     matthew  14456: =back
                   14457: 
1.191     harris41 14458: 
                   14459: =item *
                   14460: 
1.243     albertel 14461: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14462: custom role; give a custom role to a user for the level given by URL.  Specify
                   14463: name and domain of role author, and role name
1.191     harris41 14464: 
                   14465: =item *
                   14466: 
1.243     albertel 14467: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14468: 
                   14469: =item *
                   14470: 
1.243     albertel 14471: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14472: 
                   14473: =back
                   14474: 
                   14475: =head2 Course Infomation
                   14476: 
                   14477: =over 4
1.191     harris41 14478: 
                   14479: =item *
                   14480: 
1.1118    foxr     14481: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14482: specified course id, including all environment settings for the
                   14483: course, the description of the course will be in the hash under the
                   14484: key 'description'
1.191     harris41 14485: 
1.1118    foxr     14486: $options is an optional parameter that if supplied is a hash reference that controls
                   14487: what how this function works.  It has the following key/values:
                   14488: 
                   14489: =over 4
                   14490: 
                   14491: =item freshen_cache
                   14492: 
                   14493: If defined, and the environment cache for the course is valid, it is 
                   14494: returned in the returned hash.
                   14495: 
                   14496: =item one_time
                   14497: 
                   14498: If defined, the last cache time is set to _now_
                   14499: 
                   14500: =item user
                   14501: 
                   14502: If defined, the supplied username is used instead of the current user.
                   14503: 
                   14504: 
                   14505: =back
                   14506: 
1.191     harris41 14507: =item *
                   14508: 
1.624     albertel 14509: resdata($name,$domain,$type,@which) : request for current parameter
                   14510: setting for a specific $type, where $type is either 'course' or 'user',
                   14511: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14512: answers for 10 minutes.
1.243     albertel 14513: 
1.877     foxr     14514: =item *
                   14515: 
                   14516: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14517: data base, returning a hash that is keyed by the resource name and has
                   14518: values that are the resource value.  I believe that the timestamps and
                   14519: versions are also returned.
                   14520: 
1.1172.2.31  raeburn  14521: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14522: supplemental content area. This routine caches the number of files for
                   14523: 10 minutes.
                   14524: 
1.243     albertel 14525: =back
                   14526: 
                   14527: =head2 Course Modification
                   14528: 
                   14529: =over 4
1.191     harris41 14530: 
                   14531: =item *
                   14532: 
1.243     albertel 14533: writecoursepref($courseid,%prefs) : write preferences (environment
                   14534: database) for a course
1.191     harris41 14535: 
                   14536: =item *
                   14537: 
1.1011    raeburn  14538: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14539: 
                   14540: =item *
                   14541: 
1.1038    raeburn  14542: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14543: 
1.1167    droeschl 14544: =item *
                   14545: 
                   14546: is_course($courseid), is_course($cdom, $cnum)
                   14547: 
                   14548: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14549: two component version $cdom, $cnum. It checks if the specified course exists.
                   14550: 
                   14551: Returns:
                   14552:     undef if the course doesn't exist, otherwise
                   14553:     in scalar context the combined courseid.
                   14554:     in list context the two components of the course identifier, domain and 
                   14555:     courseid.    
                   14556: 
1.243     albertel 14557: =back
                   14558: 
1.1172.2.109  raeburn  14559: =head2 Bubblesheet Configuration
                   14560: 
                   14561: =over 4
                   14562: 
                   14563: =item *
                   14564: 
                   14565: get_scantron_config($which)
                   14566: 
                   14567: $which - the name of the configuration to parse from the file.
                   14568: 
                   14569: Parses and returns the bubblesheet configuration line selected as a
                   14570: hash of configuration file fields.
                   14571: 
                   14572: 
                   14573: Returns:
                   14574:     If the named configuration is not in the file, an empty
                   14575:     hash is returned.
                   14576: 
                   14577:     a hash with the fields
                   14578:       name         - internal name for the this configuration setup
                   14579:       description  - text to display to operator that describes this config
                   14580:       CODElocation - if 0 or the string 'none'
                   14581:                           - no CODE exists for this config
                   14582:                      if -1 || the string 'letter'
                   14583:                           - a CODE exists for this config and is
                   14584:                             a string of letters
                   14585:                      Unsupported value (but planned for future support)
                   14586:                           if a positive integer
                   14587:                                - The CODE exists as the first n items from
                   14588:                                  the question section of the form
                   14589:                           if the string 'number'
                   14590:                                - The CODE exists for this config and is
                   14591:                                  a string of numbers
                   14592:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14593:                      the CODE starts
                   14594:       CODElength  - length of the CODE
                   14595:       IDstart     - column where the student/employee ID starts
                   14596:       IDlength    - length of the student/employee ID info
                   14597:       Qstart      - column where the information from the bubbled
                   14598:                     'questions' start
                   14599:       Qlength     - number of columns comprising a single bubble line from
                   14600:                     the sheet. (usually either 1 or 10)
                   14601:       Qon         - either a single character representing the character used
                   14602:                     to signal a bubble was chosen in the positional setup, or
                   14603:                     the string 'letter' if the letter of the chosen bubble is
                   14604:                     in the final, or 'number' if a number representing the
                   14605:                     chosen bubble is in the file (1->A 0->J)
                   14606:       Qoff        - the character used to represent that a bubble was
                   14607:                     left blank
                   14608:       PaperID     - if the scanning process generates a unique number for each
                   14609:                     sheet scanned the column that this ID number starts in
                   14610:       PaperIDlength - number of columns that comprise the unique ID number
                   14611:                       for the sheet of paper
                   14612:       FirstName   - column that the first name starts in
                   14613:       FirstNameLength - number of columns that the first name spans
                   14614:       LastName    - column that the last name starts in
                   14615:       LastNameLength - number of columns that the last name spans
                   14616:       BubblesPerRow - number of bubbles available in each row used to
                   14617:                       bubble an answer. (If not specified, 10 assumed).
                   14618: 
                   14619: 
                   14620: =item *
                   14621: 
                   14622: get_scantronformat_file($cdom)
                   14623: 
                   14624: $cdom - the course's domain (optional); if not supplied, uses
                   14625: domain for current $env{'request.course.id'}.
                   14626: 
                   14627: Returns an array containing lines from the scantron format file for
                   14628: the domain of the course.
                   14629: 
                   14630: If a url for a custom.tab file is listed in domain's configuration.db,
                   14631: lines are from this file.
                   14632: 
                   14633: Otherwise, if a default.tab has been published in RES space by the
                   14634: domainconfig user, lines are from this file.
                   14635: 
                   14636: Otherwise, fall back to getting lines from the legacy file on the
                   14637: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14638: 
                   14639: =back
                   14640: 
1.243     albertel 14641: =head2 Resource Subroutines
                   14642: 
                   14643: =over 4
1.191     harris41 14644: 
                   14645: =item *
                   14646: 
1.243     albertel 14647: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14648: 
                   14649: =item *
                   14650: 
1.243     albertel 14651: repcopy($filename) : subscribes to the requested file, and attempts to
                   14652: replicate from the owning library server, Might return
1.607     raeburn  14653: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14654: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14655: resource. Expects the local filesystem pathname
                   14656: (/home/httpd/html/res/....)
                   14657: 
                   14658: =back
                   14659: 
                   14660: =head2 Resource Information
                   14661: 
                   14662: =over 4
1.191     harris41 14663: 
                   14664: =item *
                   14665: 
1.1172.2.28  raeburn  14666: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14667: and returns the value of a variety of different possible values,
                   14668: $varname should be a request string, and the other parameters can be
                   14669: used to specify who and what one is asking about. Ordinarily, $cid 
                   14670: does not need to be specified, as it is retrived from 
                   14671: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14672: within lonuserstate::loadmap() when initializing a course, before
                   14673: $env{'request.course.id'} has been set, so it needs to be provided
                   14674: in that one case.
1.243     albertel 14675: 
                   14676: Possible values for $varname are environment.lastname (or other item
                   14677: from the envirnment hash), user.name (or someother aspect about the
                   14678: user), resource.0.maxtries (or some other part and parameter of a
                   14679: resource)
1.204     albertel 14680: 
                   14681: =item *
                   14682: 
1.243     albertel 14683: directcondval($number) : get current value of a condition; reads from a state
                   14684: string
1.204     albertel 14685: 
                   14686: =item *
                   14687: 
1.243     albertel 14688: condval($condidx) : value of condition index based on state
1.204     albertel 14689: 
                   14690: =item *
                   14691: 
1.243     albertel 14692: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14693: resource's metadata, $what should be either a specific key, or either
                   14694: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14695: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14696: 
                   14697: this function automatically caches all requests
1.191     harris41 14698: 
                   14699: =item *
                   14700: 
1.243     albertel 14701: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14702: network of library servers; returns file handle of where SQL and regex results
                   14703: will be stored for query
1.191     harris41 14704: 
                   14705: =item *
                   14706: 
1.1172.2.66  raeburn  14707: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14708: return symbolic list entry (all arguments optional).
                   14709: 
                   14710: Args: filename is the filename (including path) for the file for which a symb
                   14711: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14712: to check access status if more than one resource was found in the bighash
                   14713: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14714: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14715: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14716: cause possible symbs to be checked to determine if they are subject to content
                   14717: blocking, if so they will not be included as possible symbs; possibles is a
                   14718: ref to a hash, which, as a side effect, will be populated with all possible
                   14719: symbs (content blocking not tested).
                   14720: 
1.243     albertel 14721: returns the data handle
1.191     harris41 14722: 
                   14723: =item *
                   14724: 
1.1172.2.17  raeburn  14725: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14726: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14727: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14728: on failure, user must be in a course, as it assumes the existence of
                   14729: the course initial hash, and uses $env('request.course.id'}.  The third
                   14730: arg is an optional reference to a scalar.  If this arg is passed in the
                   14731: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14732: encrypted; otherwise it will be null.
1.243     albertel 14733: 
1.191     harris41 14734: =item *
                   14735: 
1.243     albertel 14736: symbclean($symb) : removes versions numbers from a symb, returns the
                   14737: cleaned symb
1.191     harris41 14738: 
                   14739: =item *
                   14740: 
1.243     albertel 14741: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14742: course map, user must be in a course for it to work.
1.191     harris41 14743: 
                   14744: =item *
                   14745: 
1.243     albertel 14746: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14747: 
                   14748: =item *
                   14749: 
1.243     albertel 14750: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14751: a random seed, all arguments are optional, if they aren't sent it uses the
                   14752: environment to derive them. Note: if symb isn't sent and it can't get one
                   14753: from &symbread it will use the current time as its return value
1.191     harris41 14754: 
                   14755: =item *
                   14756: 
1.243     albertel 14757: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14758: unfakeable, receipt
1.191     harris41 14759: 
                   14760: =item *
                   14761: 
1.620     albertel 14762: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14763: 
                   14764: =item *
                   14765: 
1.243     albertel 14766: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14767: 
                   14768: =item *
                   14769: 
1.243     albertel 14770: 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 14771: 
                   14772: =item *
                   14773: 
1.243     albertel 14774: 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 14775: 
                   14776: =item *
                   14777: 
1.243     albertel 14778: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14779: 
                   14780: =item *
                   14781: 
1.243     albertel 14782: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14783: forcing spreadsheet to reevaluate the resource scores next time.
                   14784: 
1.1172.2.13  raeburn  14785: =item *
                   14786: 
                   14787: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14788: when viewing in course context.
                   14789: 
                   14790:  input: six args -- filename (decluttered), course number, course domain,
                   14791:                     url, symb (if registered) and group (if this is a
                   14792:                     group item -- e.g., bulletin board, group page etc.).
                   14793: 
                   14794:  output: array of five scalars --
                   14795:          $cfile -- url for file editing if editable on current server
                   14796:          $home -- homeserver of resource (i.e., for author if published,
                   14797:                                           or course if uploaded.).
                   14798:          $switchserver --  1 if server switch will be needed.
                   14799:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14800:          $forceview -- 1 if icon/link should be to go to view mode
                   14801: 
                   14802: =item *
                   14803: 
                   14804: is_course_upload($file,$cnum,$cdom)
                   14805: 
                   14806: Used in course context to determine if current file was uploaded to
                   14807: the course (i.e., would be found in /userfiles/docs on the course's
                   14808: homeserver.
                   14809: 
                   14810:   input: 3 args -- filename (decluttered), course number and course domain.
                   14811:   output: boolean -- 1 if file was uploaded.
                   14812: 
1.243     albertel 14813: =back
                   14814: 
                   14815: =head2 Storing/Retreiving Data
                   14816: 
                   14817: =over 4
1.191     harris41 14818: 
                   14819: =item *
                   14820: 
1.1172.2.64  raeburn  14821: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14822: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14823: the remaining args aren't required and if they aren't passed or are '' they will
                   14824: be derived from the env (with the exception of $laststore, which is an
                   14825: optional arg used when a user's submission is stored in grading).
                   14826: $laststore is $version=$timestamp, where $version is the most recent version
                   14827: number retrieved for the corresponding $symb in the $namespace db file, and
                   14828: $timestamp is the timestamp for that transaction (UNIX time).
                   14829: $laststore is currently only passed when cstore() is called by
                   14830: structuretags::finalize_storage().
1.191     harris41 14831: 
                   14832: =item *
                   14833: 
1.1172.2.64  raeburn  14834: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14835: but uses critical subroutine
1.191     harris41 14836: 
                   14837: =item *
                   14838: 
1.243     albertel 14839: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14840: all args are optional
1.191     harris41 14841: 
                   14842: =item *
                   14843: 
1.717     albertel 14844: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14845: dumps the complete (or key matching regexp) namespace into a hash
                   14846: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14847: normally &store()ed into
                   14848: 
                   14849: $range should be either an integer '100' (give me the first 100
                   14850:                                            matching records)
                   14851:               or be  two integers sperated by a - with no spaces
                   14852:                  '30-50' (give me the 30th through the 50th matching
                   14853:                           records)
                   14854: 
                   14855: 
                   14856: =item *
                   14857: 
1.1172.2.59  raeburn  14858: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14859: replaces a &store() version of data with a replacement set of data
                   14860: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14861: reference. If $tolog is true, the transaction is logged in the courselog
                   14862: with an action=PUTSTORE.
1.717     albertel 14863: 
                   14864: =item *
                   14865: 
1.243     albertel 14866: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14867: works very similar to store/cstore, but all data is stored in a
                   14868: temporary location and can be reset using tmpreset, $storehash should
                   14869: be a hash reference, returns nothing on success
1.191     harris41 14870: 
                   14871: =item *
                   14872: 
1.243     albertel 14873: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14874: similar to restore, but all data is stored in a temporary location and
                   14875: can be reset using tmpreset. Returns a hash of values on success,
                   14876: error string otherwise.
1.191     harris41 14877: 
                   14878: =item *
                   14879: 
1.243     albertel 14880: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14881: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14882: 
                   14883: =item *
                   14884: 
1.243     albertel 14885: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14886: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14887: 
                   14888: =item *
                   14889: 
1.243     albertel 14890: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14891: namesp ($udom and $uname are optional)
1.191     harris41 14892: 
                   14893: =item *
                   14894: 
1.702     albertel 14895: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14896: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14897: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14898: 
1.702     albertel 14899: $range should be either an integer '100' (give me the first 100
                   14900:                                            matching records)
                   14901:               or be  two integers sperated by a - with no spaces
                   14902:                  '30-50' (give me the 30th through the 50th matching
                   14903:                           records)
1.449     matthew  14904: =item *
                   14905: 
                   14906: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14907: $store can be a scalar, an array reference, or if the amount to be 
                   14908: incremented is > 1, a hash reference.
                   14909: 
                   14910: ($udom and $uname are optional)
1.191     harris41 14911: 
                   14912: =item *
                   14913: 
1.243     albertel 14914: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14915: ($udom and $uname are optional)
1.191     harris41 14916: 
                   14917: =item *
                   14918: 
1.243     albertel 14919: cput($namespace,$storehash,$udom,$uname) : critical put
                   14920: ($udom and $uname are optional)
1.191     harris41 14921: 
                   14922: =item *
                   14923: 
1.748     albertel 14924: newput($namespace,$storehash,$udom,$uname) :
                   14925: 
                   14926: Attempts to store the items in the $storehash, but only if they don't
                   14927: currently exist, if this succeeds you can be certain that you have 
                   14928: successfully created a new key value pair in the $namespace db.
                   14929: 
                   14930: 
                   14931: Args:
                   14932:  $namespace: name of database to store values to
                   14933:  $storehash: hashref to store to the db
                   14934:  $udom: (optional) domain of user containing the db
                   14935:  $uname: (optional) name of user caontaining the db
                   14936: 
                   14937: Returns:
                   14938:  'ok' -> succeeded in storing all keys of $storehash
                   14939:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14940:                         least <key> already existed in the db (other
                   14941:                         requested keys may also already exist)
1.967     bisitz   14942:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14943:  'con_lost' -> unable to contact request server
                   14944:  'refused' -> action was not allowed by remote machine
                   14945: 
                   14946: 
                   14947: =item *
                   14948: 
1.243     albertel 14949: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14950: reference filled in from namesp (encrypts the return communication)
                   14951: ($udom and $uname are optional)
1.191     harris41 14952: 
                   14953: =item *
                   14954: 
1.243     albertel 14955: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14956: critical subroutine
                   14957: 
1.806     raeburn  14958: =item *
                   14959: 
1.860     raeburn  14960: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14961: array reference filled in from namespace found in domain level on either
                   14962: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14963: 
                   14964: =item *
                   14965: 
1.860     raeburn  14966: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14967: domain level either on specified domain server ($uhome) or primary domain 
                   14968: server ($udom and $uhome are optional)
1.806     raeburn  14969: 
1.943     raeburn  14970: =item * 
                   14971: 
1.1172.2.35  raeburn  14972: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14973: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14974: the target domain.
                   14975: 
                   14976: May also include additional key => value pairs for the following groups:
                   14977: 
                   14978: =over
                   14979: 
                   14980: =item
                   14981: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14982: 
                   14983: =over
                   14984: 
                   14985: =item defaultquota, authorquota
                   14986: 
                   14987: =back
                   14988: 
                   14989: =item
                   14990: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14991: portfolio for users).
                   14992: 
                   14993: =over
                   14994: 
                   14995: =item
                   14996: aboutme, blog, webdav, portfolio
                   14997: 
                   14998: =back
                   14999: 
                   15000: =item
                   15001: requestcourses: ability to request courses, and how requests are processed.
                   15002: 
                   15003: =over
                   15004: 
                   15005: =item
1.1172.2.37  raeburn  15006: official, unofficial, community, textbook
1.1172.2.35  raeburn  15007: 
                   15008: =back
                   15009: 
                   15010: =item
                   15011: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15012: 
                   15013: =over
                   15014: 
                   15015: =item
1.1172.2.44  raeburn  15016: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15017: 
                   15018: =back
                   15019: 
                   15020: =item
                   15021: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15022: for course's uploaded content.
                   15023: 
                   15024: =over
                   15025: 
                   15026: =item
1.1172.2.68  raeburn  15027: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15028: communityquota, textbookquota
1.1172.2.35  raeburn  15029: 
                   15030: =back
                   15031: 
                   15032: =item
                   15033: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15034: on your servers.
                   15035: 
                   15036: =over
                   15037: 
                   15038: =item
                   15039: remotesessions, hostedsessions
                   15040: 
                   15041: =back
                   15042: 
                   15043: =back
                   15044: 
                   15045: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15046: utility to create a configuration.db file on a domain's primary library server
                   15047: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15048: -- corresponding values are authentication type (internal, krb4, krb5,
                   15049: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15050: will be available. Values are retrieved from cache (if current), unless the
                   15051: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15052: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15053: 
                   15054: Typical usage:
1.943     raeburn  15055: 
1.1172.2.35  raeburn  15056: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15057: 
1.243     albertel 15058: =back
                   15059: 
                   15060: =head2 Network Status Functions
                   15061: 
                   15062: =over 4
1.191     harris41 15063: 
                   15064: =item *
                   15065: 
1.1137    raeburn  15066: dirlist() : return directory list based on URI (first arg).
                   15067: 
                   15068: Inputs: 1 required, 5 optional.
                   15069: 
                   15070: =over
                   15071: 
                   15072: =item 
                   15073: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15074: 
                   15075: =item
                   15076: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15077: 
                   15078: =item
                   15079: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15080: 
                   15081: =item
                   15082: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15083: 
                   15084: =item
                   15085: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15086: 
                   15087: =item 
                   15088: $alternateRoot - path to prepend in place of path from $uri.
                   15089: 
                   15090: =back
                   15091: 
                   15092: Returns: Array of up to two items.
                   15093: 
                   15094: =over
                   15095: 
                   15096: a reference to an array of files/subdirectories
                   15097: 
                   15098: =over
                   15099: 
                   15100: Each element in the array of files/subdirectories is a & separated list of
                   15101: item name and the result of running stat on the item.  If dirlist was requested
                   15102: for a file instead of a directory, the item name will be ''. For a directory 
                   15103: listing, if the item is a metadata file, the element will end &N&M 
                   15104: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15105: default copyright set (1).  
                   15106: 
                   15107: =back
                   15108: 
                   15109: a scalar containing error condition (if encountered).
                   15110: 
                   15111: =over
                   15112: 
                   15113: =item 
                   15114: no_host (no homeserver identified for $username:$domain).
                   15115: 
                   15116: =item 
                   15117: no_such_host (server contacted for listing not identified as valid host).
                   15118: 
                   15119: =item 
                   15120: con_lost (connection to remote server failed).
                   15121: 
                   15122: =item 
                   15123: refused (invalid $username:$domain received on lond side).
                   15124: 
                   15125: =item 
                   15126: no_such_dir (directory at specified path on lond side does not exist). 
                   15127: 
                   15128: =item 
                   15129: empty (directory at specified path on lond side is empty).
                   15130: 
                   15131: =over
                   15132: 
                   15133: This is currently not encountered because the &ls3, &ls2, 
                   15134: &ls (_handler) routines on the lond side do not filter out
                   15135: . and .. from a directory listing. 
                   15136: 
                   15137: =back
                   15138: 
                   15139: =back
                   15140: 
                   15141: =back
1.191     harris41 15142: 
                   15143: =item *
                   15144: 
1.243     albertel 15145: spareserver() : find server with least workload from spare.tab
                   15146: 
1.986     foxr     15147: 
                   15148: =item *
                   15149: 
                   15150: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15151: if there is no corresponding loncapa host.
                   15152: 
1.243     albertel 15153: =back
                   15154: 
1.986     foxr     15155: 
1.243     albertel 15156: =head2 Apache Request
                   15157: 
                   15158: =over 4
1.191     harris41 15159: 
                   15160: =item *
                   15161: 
1.243     albertel 15162: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15163: localhost, posts hash
                   15164: 
                   15165: =back
                   15166: 
                   15167: =head2 Data to String to Data
                   15168: 
                   15169: =over 4
1.191     harris41 15170: 
                   15171: =item *
                   15172: 
1.243     albertel 15173: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15174: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15175: 
                   15176: =item *
                   15177: 
1.243     albertel 15178: hashref2str($hashref) : convert a hashref into a string complete with
                   15179: escaping and '=' and '&' separators, supports elements that are
                   15180: arrayrefs and hashrefs
1.191     harris41 15181: 
                   15182: =item *
                   15183: 
1.243     albertel 15184: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15185: with escaping and '&' separators, supports elements that are arrayrefs
                   15186: and hashrefs
1.191     harris41 15187: 
                   15188: =item *
                   15189: 
1.243     albertel 15190: str2hash($string) : convert string to hash using unescaping and
                   15191: splitting on '=' and '&', supports elements that are arrayrefs and
                   15192: hashrefs
1.191     harris41 15193: 
                   15194: =item *
                   15195: 
1.243     albertel 15196: str2array($string) : convert string to hash using unescaping and
                   15197: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15198: 
                   15199: =back
                   15200: 
                   15201: =head2 Logging Routines
                   15202: 
                   15203: 
                   15204: These routines allow one to make log messages in the lonnet.log and
                   15205: lonnet.perm logfiles.
1.191     harris41 15206: 
1.1119    foxr     15207: =over 4
                   15208: 
1.191     harris41 15209: =item *
                   15210: 
1.243     albertel 15211: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15212: 
                   15213: =item *
                   15214: 
1.243     albertel 15215: logthis() : append message to the normal lonnet.log file, it gets
                   15216: preiodically rolled over and deleted.
1.191     harris41 15217: 
                   15218: =item *
                   15219: 
1.243     albertel 15220: logperm() : append a permanent message to lonnet.perm.log, this log
                   15221: file never gets deleted by any automated portion of the system, only
                   15222: messages of critical importance should go in here.
                   15223: 
1.1119    foxr     15224: 
1.243     albertel 15225: =back
                   15226: 
                   15227: =head2 General File Helper Routines
                   15228: 
                   15229: =over 4
1.191     harris41 15230: 
                   15231: =item *
                   15232: 
1.481     raeburn  15233: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15234: (a) files in /uploaded
                   15235:   (i) If a local copy of the file exists - 
                   15236:       compares modification date of local copy with last-modified date for 
                   15237:       definitive version stored on home server for course. If local copy is 
                   15238:       stale, requests a new version from the home server and stores it. 
                   15239:       If the original has been removed from the home server, then local copy 
                   15240:       is unlinked.
                   15241:   (ii) If local copy does not exist -
                   15242:       requests the file from the home server and stores it. 
                   15243:   
                   15244:   If $caller is 'uploadrep':  
                   15245:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15246:     for request for files originally uploaded via DOCS. 
                   15247:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15248:   
                   15249:   Otherwise:
                   15250:      This indicates a call from the content generation phase of the request.
                   15251:      -  returns the entire contents of the file or -1.
                   15252:      
                   15253: (b) files in /res
                   15254:    - returns the entire contents of a file or -1; 
                   15255:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15256: 
1.712     albertel 15257: 
                   15258: =item *
                   15259: 
                   15260: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15261:                   reference
                   15262: 
                   15263: returns either a stat() list of data about the file or an empty list
                   15264: if the file doesn't exist or couldn't find out about it (connection
                   15265: problems or user unknown)
                   15266: 
1.191     harris41 15267: =item *
                   15268: 
1.243     albertel 15269: filelocation($dir,$file) : returns file system location of a file
                   15270: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15271: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15272: and a file of ../bob will become /a/bob)
1.191     harris41 15273: 
                   15274: =item *
                   15275: 
                   15276: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15277: filelocation except for hrefs
                   15278: 
                   15279: =item *
                   15280: 
1.1172.2.49  raeburn  15281: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15282: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15283: 
1.243     albertel 15284: =back
                   15285: 
1.608     albertel 15286: =head2 Usererfile file routines (/uploaded*)
                   15287: 
                   15288: =over 4
                   15289: 
                   15290: =item *
                   15291: 
                   15292: userfileupload(): main rotine for putting a file in a user or course's
                   15293:                   filespace, arguments are,
                   15294: 
1.620     albertel 15295:  formname - required - this is the name of the element in $env where the
1.608     albertel 15296:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15297:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15298:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15299:  context - if coursedoc, store the file in the course of the active role
                   15300:              of the current user; 
                   15301:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15302:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15303:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15304:          if undefined, it will be placed in "unknown"
                   15305: 
                   15306:  (This routine calls clean_filename() to remove any dangerous
                   15307:  characters from the filename, and then calls finuserfileupload() to
                   15308:  complete the transaction)
                   15309: 
                   15310:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15311:  and /adm/notfound.html if unsuccessful
                   15312: 
                   15313: =item *
                   15314: 
                   15315: clean_filename(): routine for cleaing a filename up for storage in
                   15316:                  userfile space, argument is:
                   15317: 
                   15318:  filename - proposed filename
                   15319: 
                   15320: returns: the new clean filename
                   15321: 
                   15322: =item *
                   15323: 
1.1090    raeburn  15324: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15325: userspace, probably shouldn't be called directly
                   15326: 
                   15327:   docuname: username or courseid of destination for the file
                   15328:   docudom: domain of user/course of destination for the file
                   15329:   formname: same as for userfileupload()
1.1090    raeburn  15330:   fname: filename (including subdirectories) for the file
                   15331:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15332:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15333:   allfiles: reference to hash used to store objects found by parser
                   15334:   codebase: reference to hash used for codebases of java objects found by parser
                   15335:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15336:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15337:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15338:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15339:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15340:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15341:   mimetype: reference to scalar to accommodate mime type determined
                   15342:             from File::MMagic if $parser = parse.
1.608     albertel 15343: 
                   15344:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15345:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15346:  was 'overwrite').
                   15347:  
1.608     albertel 15348: 
                   15349: =item *
                   15350: 
                   15351: renameuserfile(): renames an existing userfile to a new name
                   15352: 
                   15353:   Args:
                   15354:    docuname: username or courseid of destination for the file
                   15355:    docudom: domain of user/course of destination for the file
                   15356:    old: current file name (including any subdirs under userfiles)
                   15357:    new: desired file name (including any subdirs under userfiles)
                   15358: 
                   15359: =item *
                   15360: 
                   15361: mkdiruserfile(): creates a directory is a userfiles dir
                   15362: 
                   15363:   Args:
                   15364:    docuname: username or courseid of destination for the file
                   15365:    docudom: domain of user/course of destination for the file
                   15366:    dir: dir to create (including any subdirs under userfiles)
                   15367: 
                   15368: =item *
                   15369: 
                   15370: removeuserfile(): removes a file that exists in userfiles
                   15371: 
                   15372:   Args:
                   15373:    docuname: username or courseid of destination for the file
                   15374:    docudom: domain of user/course of destination for the file
                   15375:    fname: filname to delete (including any subdirs under userfiles)
                   15376: 
                   15377: =item *
                   15378: 
                   15379: removeuploadedurl(): convience function for removeuserfile()
                   15380: 
                   15381:   Args:
                   15382:    url:  a full /uploaded/... url to delete
                   15383: 
1.747     albertel 15384: =item * 
                   15385: 
                   15386: get_portfile_permissions():
                   15387:   Args:
                   15388:     domain: domain of user or course contain the portfolio files
                   15389:     user: name of user or num of course contain the portfolio files
                   15390:   Returns:
                   15391:     hashref of a dump of the proper file_permissions.db
                   15392:    
                   15393: 
                   15394: =item * 
                   15395: 
                   15396: get_access_controls():
                   15397: 
                   15398: Args:
                   15399:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15400:   group: (optional) the group you want the files associated with
                   15401:   file: (optional) the file you want access info on
                   15402: 
                   15403: Returns:
1.749     raeburn  15404:     a hash (keys are file names) of hashes containing
                   15405:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15406:         values are XML containing access control settings (see below) 
1.747     albertel 15407: 
                   15408: Internal notes:
                   15409: 
1.749     raeburn  15410:  access controls are stored in file_permissions.db as key=value pairs.
                   15411:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15412:         where scope -> public,guest,course,group,domains or users.
                   15413:               end -> UNIX time for end of access (0 -> no end date)
                   15414:               start -> UNIX time for start of access
                   15415: 
                   15416:     value -> XML description of access control
                   15417:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15418:             <start></start>
                   15419:             <end></end>
                   15420: 
                   15421:             <password></password>  for scope type = guest
                   15422: 
                   15423:             <domain></domain>     for scope type = course or group
                   15424:             <number></number>
                   15425:             <roles id="">
                   15426:              <role></role>
                   15427:              <access></access>
                   15428:              <section></section>
                   15429:              <group></group>
                   15430:             </roles>
                   15431: 
                   15432:             <dom></dom>         for scope type = domains
                   15433: 
                   15434:             <users>             for scope type = users
                   15435:              <user>
                   15436:               <uname></uname>
                   15437:               <udom></udom>
                   15438:              </user>
                   15439:             </users>
                   15440:            </scope> 
                   15441:               
                   15442:  Access data is also aggregated for each file in an additional key=value pair:
                   15443:  key -> path to file/file_name\0accesscontrol 
                   15444:  value -> reference to hash
                   15445:           hash contains key = value pairs
                   15446:           where key = uniqueID:scope_end_start
                   15447:                 value = UNIX time record was last updated
                   15448: 
                   15449:           Used to improve speed of look-ups of access controls for each file.  
                   15450:  
                   15451:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15452: 
1.1172.2.13  raeburn  15453: =item *
                   15454: 
1.749     raeburn  15455: modify_access_controls():
                   15456: 
                   15457: Modifies access controls for a portfolio file
                   15458: Args
                   15459: 1. file name
                   15460: 2. reference to hash of required changes,
                   15461: 3. domain
                   15462: 4. username
                   15463:   where domain,username are the domain of the portfolio owner 
                   15464:   (either a user or a course) 
                   15465: 
                   15466: Returns:
                   15467: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15468: 2. result of deletions ('ok' or 'error', with error message).
                   15469: 3. reference to hash of any new or updated access controls.
                   15470: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15471:    key = integer (inbound ID)
1.1172.2.13  raeburn  15472:    value = uniqueID
                   15473: 
                   15474: =item *
                   15475: 
                   15476: get_timebased_id():
                   15477: 
                   15478: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15479: course via the Course Editor (e.g., folders, composite pages,
                   15480: group bulletin boards).
                   15481: 
                   15482: Args: (first three required; six others optional)
                   15483: 
                   15484: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15485:    docssequence, or name of group
                   15486: 
                   15487: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15488:    e.g., num, boardids
                   15489: 
                   15490: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15491:    file will be named nohist_namespace.db
                   15492: 
                   15493: 4. cdom: domain of course; default is current course domain from %env
                   15494: 
                   15495: 5. cnum: course number; default is current course number from %env
                   15496: 
                   15497: 6. idtype: set to concat if an additional digit is to be appended to the
                   15498:    unix timestamp to form the suffix, if the plain timestamp is already
                   15499:    in use.  Default is to not do this, but simply increment the unix
                   15500:    timestamp by 1 until a unique key is obtained.
                   15501: 
                   15502: 7. who: holder of locking key; defaults to user:domain for user.
                   15503: 
                   15504: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15505:    retrying); default is 3.
                   15506: 
                   15507: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15508: 
                   15509: Returns:
                   15510: 
                   15511: 1. suffix obtained (numeric)
                   15512: 
                   15513: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15514: 
                   15515: 3. error: contains (localized) error message if an error occurred.
                   15516: 
1.747     albertel 15517: 
1.608     albertel 15518: =back
                   15519: 
1.243     albertel 15520: =head2 HTTP Helper Routines
                   15521: 
                   15522: =over 4
                   15523: 
1.191     harris41 15524: =item *
                   15525: 
                   15526: escape() : unpack non-word characters into CGI-compatible hex codes
                   15527: 
                   15528: =item *
                   15529: 
                   15530: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15531: 
1.243     albertel 15532: =back
                   15533: 
                   15534: =head1 PRIVATE SUBROUTINES
                   15535: 
                   15536: =head2 Underlying communication routines (Shouldn't call)
                   15537: 
                   15538: =over 4
                   15539: 
                   15540: =item *
                   15541: 
                   15542: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15543: 
                   15544: =item *
                   15545: 
                   15546: reply() : uses subreply to send a message to remote machine, logs all failures
                   15547: 
                   15548: =item *
                   15549: 
                   15550: critical() : passes a critical message to another server; if cannot
                   15551: get through then place message in connection buffer directory and
                   15552: returns con_delayed, if incapable of saving message, returns
                   15553: con_failed
                   15554: 
                   15555: =item *
                   15556: 
                   15557: reconlonc() : tries to reconnect lonc client processes.
                   15558: 
                   15559: =back
                   15560: 
                   15561: =head2 Resource Access Logging
                   15562: 
                   15563: =over 4
                   15564: 
                   15565: =item *
                   15566: 
                   15567: flushcourselogs() : flush (save) buffer logs and access logs
                   15568: 
                   15569: =item *
                   15570: 
                   15571: courselog($what) : save message for course in hash
                   15572: 
                   15573: =item *
                   15574: 
                   15575: courseacclog($what) : save message for course using &courselog().  Perform
                   15576: special processing for specific resource types (problems, exams, quizzes, etc).
                   15577: 
1.191     harris41 15578: =item *
                   15579: 
                   15580: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15581: as a PerlChildExitHandler
1.243     albertel 15582: 
                   15583: =back
                   15584: 
                   15585: =head2 Other
                   15586: 
                   15587: =over 4
                   15588: 
                   15589: =item *
                   15590: 
                   15591: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15592: 
                   15593: =back
                   15594: 
                   15595: =cut
1.877     foxr     15596: 

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