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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.114! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.113 2019/08/22 00:16:39 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114! raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1172.2.110  raeburn   102: use LONCAPA::transliterate;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.1172.2.79  raeburn   107: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.1172.2.9  raeburn   114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       115: {
                    116:     my $logid;
1.1172.2.9  raeburn   117:     sub write_log {
                    118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    119:         if ($context eq 'course') {
                    120:             if (($cnum eq '') || ($cdom eq '')) {
                    121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:             }
1.957     raeburn   124:         }
1.1172.2.13  raeburn   125: 	$logid ++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   128:         my $logentry = {
                    129:                          $id => {
                    130:                                   'exe_uname' => $env{'user.name'},
                    131:                                   'exe_udom'  => $env{'user.domain'},
                    132:                                   'exe_time'  => $now,
                    133:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    134:                                   'delflag'   => $delflag,
                    135:                                   'logentry'  => $storehash,
                    136:                                   'uname'     => $uname,
                    137:                                   'udom'      => $udom,
                    138:                                 }
                    139:                        };
                    140:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       141:     }
                    142: }
1.1       albertel  143: 
1.163     harris41  144: sub logtouch {
                    145:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  146:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   147: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  148: 	close $fh;
                    149:     }
                    150:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    151:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    152: }
                    153: 
1.1       albertel  154: sub logthis {
                    155:     my $message=shift;
                    156:     my $execdir=$perlvar{'lonDaemons'};
                    157:     my $now=time;
                    158:     my $local=localtime($now);
1.1172.2.96  raeburn   159:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      160: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    161: 	print $fh $logstring;
1.448     albertel  162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
                    167: sub logperm {
                    168:     my $message=shift;
                    169:     my $execdir=$perlvar{'lonDaemons'};
                    170:     my $now=time;
                    171:     my $local=localtime($now);
1.1172.2.96  raeburn   172:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  173: 	print $fh "$now:$message:$local\n";
                    174: 	close($fh);
                    175:     }
1.1       albertel  176:     return 1;
                    177: }
                    178: 
1.850     albertel  179: sub create_connection {
1.853     albertel  180:     my ($hostname,$lonid) = @_;
1.851     albertel  181:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  182: 				     Type    => SOCK_STREAM,
                    183: 				     Timeout => 10);
                    184:     return 0 if (!$client);
1.890     albertel  185:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  186:     my $result = <$client>;
                    187:     chomp($result);
                    188:     return 1 if ($result eq 'done');
                    189:     return 0;
                    190: }
                    191: 
1.983     raeburn   192: sub get_server_timezone {
                    193:     my ($cnum,$cdom) = @_;
                    194:     my $home=&homeserver($cnum,$cdom);
                    195:     if ($home ne 'no_host') {
                    196:         my $cachetime = 24*3600;
                    197:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    198:         if (defined($cached)) {
                    199:             return $timezone;
                    200:         } else {
                    201:             my $timezone = &reply('servertimezone',$home);
                    202:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    203:         }
                    204:     }
                    205: }
1.850     albertel  206: 
1.1106    raeburn   207: sub get_server_distarch {
                    208:     my ($lonhost,$ignore_cache) = @_;
                    209:     if (defined($lonhost)) {
                    210:         if (!defined(&hostname($lonhost))) {
                    211:             return;
                    212:         }
                    213:         my $cachetime = 12*3600;
                    214:         if (!$ignore_cache) {
                    215:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    216:             if (defined($cached)) {
                    217:                 return $distarch;
                    218:             }
                    219:         }
                    220:         my $rep = &reply('serverdistarch',$lonhost);
                    221:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    222:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    223:                 $rep eq '') {
                    224:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    225:         }
                    226:     }
                    227:     return;
                    228: }
                    229: 
1.993     raeburn   230: sub get_server_loncaparev {
1.1073    raeburn   231:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   232:     if (defined($lonhost)) {
                    233:         if (!defined(&hostname($lonhost))) {
                    234:             undef($lonhost);
                    235:         }
                    236:     }
                    237:     if (!defined($lonhost)) {
                    238:         if (defined(&domain($dom,'primary'))) {
                    239:             $lonhost=&domain($dom,'primary');
                    240:             if ($lonhost eq 'no_host') {
                    241:                 undef($lonhost);
                    242:             }
                    243:         }
                    244:     }
                    245:     if (defined($lonhost)) {
1.1073    raeburn   246:         my $cachetime = 12*3600;
                    247:         if (!$ignore_cache) {
                    248:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    249:             if (defined($cached)) {
                    250:                 return $loncaparev;
                    251:             }
                    252:         }
                    253:         my ($answer,$loncaparev);
                    254:         my @ids=&current_machine_ids();
                    255:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    256:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   257:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   258:                 $loncaparev = $1;
                    259:             }
                    260:         } else {
                    261:             $answer = &reply('serverloncaparev',$lonhost);
                    262:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    263:                 if ($caller eq 'loncron') {
                    264:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   265:                     $ua->timeout(4);
1.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.1172.2.113  raeburn  1199:     } elsif ($answer =~ "^prioruse") {
                   1200:        &logthis("$server refused to change $uname in $udom password because ".
                   1201:                 "the password had been used before");
1.202     matthew  1202:     }
                   1203:     return $answer;
1.1       albertel 1204: }
                   1205: 
1.169     harris41 1206: # ----------------------- Try to determine user's current authentication scheme
                   1207: 
                   1208: sub queryauthenticate {
                   1209:     my ($uname,$udom)=@_;
1.456     albertel 1210:     my $uhome=&homeserver($uname,$udom);
                   1211:     if (!$uhome) {
                   1212: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1213: 	return 'no_host';
                   1214:     }
                   1215:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1216:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1217: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1218:     }
1.456     albertel 1219:     return $answer;
1.169     harris41 1220: }
                   1221: 
1.1       albertel 1222: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1223: 
1.1       albertel 1224: sub authenticate {
1.1073    raeburn  1225:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1226:     $upass=&escape($upass);
                   1227:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1228:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1229:     my $newhome;
1.836     www      1230:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1231: # Maybe the machine was offline and only re-appeared again recently?
                   1232:         &reconlonc();
                   1233: # One more
1.952     raeburn  1234: 	$uhome=&homeserver($uname,$udom,1);
                   1235:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1236:             if (defined(&domain($udom,'primary'))) {
                   1237:                 $newhome=&domain($udom,'primary');
                   1238:             }
                   1239:             if ($newhome ne '') {
                   1240:                 $uhome = $newhome;
                   1241:             }
                   1242:         }
1.836     www      1243: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1244: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1245: 	    return 'no_host';
                   1246:         }
1.1       albertel 1247:     }
1.1073    raeburn  1248:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1249:     if ($answer eq 'authorized') {
1.952     raeburn  1250:         if ($newhome) {
                   1251:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1252:             return 'no_account_on_host'; 
                   1253:         } else {
                   1254:             &logthis("User $uname at $udom authorized by $uhome");
                   1255:             return $uhome;
                   1256:         }
1.471     albertel 1257:     }
                   1258:     if ($answer eq 'non_authorized') {
                   1259: 	&logthis("User $uname at $udom rejected by $uhome");
                   1260: 	return 'no_host'; 
1.9       www      1261:     }
1.471     albertel 1262:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1263:     return 'no_host';
                   1264: }
                   1265: 
1.1073    raeburn  1266: sub can_host_session {
1.1074    raeburn  1267:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1268:     my $canhost = 1;
1.1074    raeburn  1269:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1270:     if (ref($remotesessions) eq 'HASH') {
                   1271:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1272:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1273:                 $canhost = 0;
                   1274:             } else {
                   1275:                 $canhost = 1;
                   1276:             }
                   1277:         }
                   1278:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1279:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1280:                 $canhost = 1;
                   1281:             } else {
                   1282:                 $canhost = 0;
                   1283:             }
                   1284:         }
                   1285:         if ($canhost) {
                   1286:             if ($remotesessions->{'version'} ne '') {
                   1287:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1288:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1289:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1290:                         my $major = $1;
                   1291:                         my $minor = $2;
                   1292:                         if (($major < $reqmajor ) ||
                   1293:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1294:                             $canhost = 0;
                   1295:                         }
                   1296:                     } else {
                   1297:                         $canhost = 0;
                   1298:                     }
                   1299:                 }
                   1300:             }
                   1301:         }
                   1302:     }
                   1303:     if ($canhost) {
                   1304:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1305:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1306:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1307:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1308:                 if (($uint_dom ne '') && 
                   1309:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1310:                     $canhost = 0;
                   1311:                 } else {
                   1312:                     $canhost = 1;
                   1313:                 }
                   1314:             }
                   1315:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1316:                 if (($uint_dom ne '') && 
                   1317:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1318:                     $canhost = 1;
                   1319:                 } else {
                   1320:                     $canhost = 0;
                   1321:                 }
                   1322:             }
                   1323:         }
                   1324:     }
                   1325:     return $canhost;
                   1326: }
                   1327: 
1.1083    raeburn  1328: sub spare_can_host {
                   1329:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1330:     my $canhost=1;
1.1172.2.62  raeburn  1331:     my $try_server_hostname = &hostname($try_server);
                   1332:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1333:     my $serverhomedom = &host_domain($serverhomeID);
                   1334:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1335:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1336:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1337:             $canhost = 0;
                   1338:         }
                   1339:     }
                   1340:     if (($canhost) && ($uint_dom)) {
                   1341:         my @intdoms;
                   1342:         my $internet_names = &get_internet_names($try_server);
                   1343:         if (ref($internet_names) eq 'ARRAY') {
                   1344:             @intdoms = @{$internet_names};
                   1345:         }
                   1346:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1347:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1348:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1349:                                          $remotesessions,
                   1350:                                          $defdomdefaults{'hostedsessions'});
                   1351:         }
1.1083    raeburn  1352:     }
                   1353:     return $canhost;
                   1354: }
                   1355: 
1.1123    raeburn  1356: sub this_host_spares {
                   1357:     my ($dom) = @_;
1.1126    raeburn  1358:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1359:     my @hosts = &current_machine_ids();
                   1360:     foreach my $lonhost (@hosts) {
                   1361:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1362:             $dom_in_use = $dom;
                   1363:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1364:             last;
                   1365:         }
                   1366:     }
1.1126    raeburn  1367:     if ($dom_in_use ne '') {
                   1368:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1369:     }
                   1370:     if (ref($result) ne 'HASH') {
                   1371:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1372:         $dom_in_use = &host_domain($lonhost_in_use);
                   1373:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1374:         if (ref($result) ne 'HASH') {
                   1375:             $result = \%spareid;
                   1376:         }
                   1377:     }
                   1378:     return $result;
                   1379: }
                   1380: 
                   1381: sub spares_for_offload  {
                   1382:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1383:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1384:     if (defined($cached)) {
                   1385:         return $result;
                   1386:     } else {
1.1126    raeburn  1387:         my $cachetime = 60*60*24;
                   1388:         my %domconfig =
                   1389:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1390:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1391:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1392:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1393:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1394:                 }
                   1395:             }
                   1396:         }
                   1397:     }
1.1126    raeburn  1398:     return;
1.1123    raeburn  1399: }
                   1400: 
1.1129    raeburn  1401: sub get_lonbalancer_config {
                   1402:     my ($servers) = @_;
                   1403:     my ($currbalancer,$currtargets);
                   1404:     if (ref($servers) eq 'HASH') {
                   1405:         foreach my $server (keys(%{$servers})) {
                   1406:             my %what = (
                   1407:                          spareid => 1,
                   1408:                          perlvar => 1,
                   1409:                        );
                   1410:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1411:             if ($result eq 'ok') {
                   1412:                 if (ref($returnhash) eq 'HASH') {
                   1413:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1414:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1415:                             $currbalancer = $server;
                   1416:                             $currtargets = {};
                   1417:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1418:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1419:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1420:                                 }
                   1421:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1422:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1423:                                 }
                   1424:                             }
                   1425:                             last;
                   1426:                         }
                   1427:                     }
                   1428:                 }
                   1429:             }
                   1430:         }
                   1431:     }
                   1432:     return ($currbalancer,$currtargets);
                   1433: }
                   1434: 
                   1435: sub check_loadbalancing {
1.1172.2.88  raeburn  1436:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1437:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1438:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1439:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1440:     my @hosts = &current_machine_ids();
1.1129    raeburn  1441:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1442:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1443:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1444:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1445:     my $domneedscache; 
1.1129    raeburn  1446:     my $cachetime = 60*60*24;
                   1447: 
                   1448:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1449:         $dom_in_use = $udom;
                   1450:         $homeintdom = 1;
                   1451:     } else {
                   1452:         $dom_in_use = $serverhomedom;
                   1453:     }
                   1454:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1455:     unless (defined($cached)) {
                   1456:         my %domconfig =
                   1457:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1458:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1459:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1460:         } else {
                   1461:             $domneedscache = $dom_in_use;
1.1129    raeburn  1462:         }
                   1463:     }
                   1464:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1465:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1466:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1467:         if ($is_balancer) {
                   1468:             if (ref($currrules) eq 'HASH') {
                   1469:                 if ($homeintdom) {
                   1470:                     if ($uname ne '') {
                   1471:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1472:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1473:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1474:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1475:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1476:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1477:                             }
                   1478:                         }
                   1479:                         if ($rule_in_effect eq '') {
                   1480:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1481:                             if ($userenv{'inststatus'} ne '') {
                   1482:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1483:                                 my ($othertitle,$usertypes,$types) =
                   1484:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1485:                                 if (ref($types) eq 'ARRAY') {
                   1486:                                     foreach my $type (@{$types}) {
                   1487:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1488:                                             if (exists($currrules->{$type})) {
                   1489:                                                 $rule_in_effect = $currrules->{$type};
                   1490:                                             }
                   1491:                                         }
                   1492:                                     }
                   1493:                                 }
                   1494:                             } else {
                   1495:                                 if (exists($currrules->{'default'})) {
                   1496:                                     $rule_in_effect = $currrules->{'default'};
                   1497:                                 }
                   1498:                             }
                   1499:                         }
                   1500:                     } else {
                   1501:                         if (exists($currrules->{'default'})) {
                   1502:                             $rule_in_effect = $currrules->{'default'};
                   1503:                         }
                   1504:                     }
                   1505:                 } else {
                   1506:                     if ($currrules->{'_LC_external'} ne '') {
                   1507:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1508:                     }
                   1509:                 }
                   1510:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1511:                                                        $uname,$udom);
                   1512:             }
                   1513:         }
                   1514:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1515:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1516:         unless (defined($cached)) {
                   1517:             my %domconfig =
                   1518:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1519:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1520:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1521:             } else {
                   1522:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1523:             }
                   1524:         }
                   1525:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1526:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1527:                 &check_balancer_result($result,@hosts);
                   1528:             if ($is_balancer) {
1.1129    raeburn  1529:                 if (ref($currrules) eq 'HASH') {
                   1530:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1531:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1532:                     }
                   1533:                 }
                   1534:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1535:                                                        $uname,$udom);
                   1536:             }
                   1537:         } else {
                   1538:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1539:                 $is_balancer = 1;
                   1540:                 $offloadto = &this_host_spares($dom_in_use);
                   1541:             }
1.1172.2.75  raeburn  1542:             unless (defined($cached)) {
                   1543:                 $domneedscache = $serverhomedom;
                   1544:             }
1.1129    raeburn  1545:         }
                   1546:     } else {
                   1547:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1548:             $is_balancer = 1;
                   1549:             $offloadto = &this_host_spares($dom_in_use);
                   1550:         }
1.1172.2.75  raeburn  1551:         unless (defined($cached)) {
                   1552:             $domneedscache = $serverhomedom;
                   1553:         }
                   1554:     }
                   1555:     if ($domneedscache) {
                   1556:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1557:     }
1.1172.2.5  raeburn  1558:     if ($is_balancer) {
                   1559:         my $lowest_load = 30000;
                   1560:         if (ref($offloadto) eq 'HASH') {
                   1561:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1562:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1563:                     ($otherserver,$lowest_load) =
                   1564:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1565:                 }
1.1129    raeburn  1566:             }
1.1172.2.5  raeburn  1567:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1568: 
1.1172.2.5  raeburn  1569:             if (!$found_server) {
                   1570:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1571:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1572:                         ($otherserver,$lowest_load) =
                   1573:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1574:                     }
                   1575:                 }
                   1576:             }
                   1577:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1578:             if (@{$offloadto} == 1) {
                   1579:                 $otherserver = $offloadto->[0];
                   1580:             } elsif (@{$offloadto} > 1) {
                   1581:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1582:                     ($otherserver,$lowest_load) =
                   1583:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1584:                 }
                   1585:             }
                   1586:         }
1.1172.2.88  raeburn  1587:         unless ($caller eq 'login') {
                   1588:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1589:                 $is_balancer = 0;
                   1590:                 if ($uname ne '' && $udom ne '') {
                   1591:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1592:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1593:                                  'user.loadbalcheck.time' => time});
                   1594:                     }
1.1172.2.5  raeburn  1595:                 }
1.1129    raeburn  1596:             }
                   1597:         }
1.1172.2.107  raeburn  1598:         unless ($homeintdom) {
                   1599:             undef($setcookie);
                   1600:         }
1.1129    raeburn  1601:     }
1.1172.2.107  raeburn  1602:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1603: }
                   1604: 
1.1172.2.12  raeburn  1605: sub check_balancer_result {
                   1606:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1607:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1608:     if (ref($result) eq 'HASH') {
                   1609:         if ($result->{'lonhost'} ne '') {
                   1610:             my $currbalancer = $result->{'lonhost'};
                   1611:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1612:                 $is_balancer = 1;
                   1613:                 $currtargets = $result->{'targets'};
                   1614:                 $currrules = $result->{'rules'};
                   1615:             }
                   1616:         } else {
                   1617:             foreach my $key (keys(%{$result})) {
                   1618:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1619:                     (ref($result->{$key}) eq 'HASH')) {
                   1620:                     $is_balancer = 1;
                   1621:                     $currrules = $result->{$key}{'rules'};
                   1622:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1623:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1624:                     last;
                   1625:                 }
                   1626:             }
                   1627:         }
                   1628:     }
1.1172.2.107  raeburn  1629:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1630: }
                   1631: 
1.1129    raeburn  1632: sub get_loadbalancer_targets {
                   1633:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1634:     my $offloadto;
1.1172.2.4  raeburn  1635:     if ($rule_in_effect eq 'none') {
                   1636:         return [$perlvar{'lonHostID'}];
                   1637:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1638:         $offloadto = $currtargets;
                   1639:     } else {
                   1640:         if ($rule_in_effect eq 'homeserver') {
                   1641:             my $homeserver = &homeserver($uname,$udom);
                   1642:             if ($homeserver ne 'no_host') {
                   1643:                 $offloadto = [$homeserver];
                   1644:             }
                   1645:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1646:             my %domconfig =
                   1647:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1648:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1649:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1650:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1651:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1652:                     }
                   1653:                 }
                   1654:             } else {
1.1172.2.7  raeburn  1655:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1656:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1657:                 if (&hostname($remotebalancer) ne '') {
                   1658:                     $offloadto = [$remotebalancer];
                   1659:                 }
                   1660:             }
                   1661:         } elsif (&hostname($rule_in_effect) ne '') {
                   1662:             $offloadto = [$rule_in_effect];
                   1663:         }
                   1664:     }
                   1665:     return $offloadto;
                   1666: }
                   1667: 
1.1127    raeburn  1668: sub internet_dom_servers {
                   1669:     my ($dom) = @_;
                   1670:     my (%uniqservers,%servers);
                   1671:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1672:     my @machinedoms = &machine_domains($primaryserver);
                   1673:     foreach my $mdom (@machinedoms) {
                   1674:         my %currservers = %servers;
                   1675:         my %server = &get_servers($mdom);
                   1676:         %servers = (%currservers,%server);
                   1677:     }
                   1678:     my %by_hostname;
                   1679:     foreach my $id (keys(%servers)) {
                   1680:         push(@{$by_hostname{$servers{$id}}},$id);
                   1681:     }
                   1682:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1683:         if (@{$by_hostname{$hostname}} > 1) {
                   1684:             my $match = 0;
                   1685:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1686:                 if (&host_domain($id) eq $dom) {
                   1687:                     $uniqservers{$id} = $hostname;
                   1688:                     $match = 1;
                   1689:                 }
                   1690:             }
                   1691:             unless ($match) {
                   1692:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1693:             }
                   1694:         } else {
                   1695:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1696:         }
                   1697:     }
                   1698:     return %uniqservers;
                   1699: }
                   1700: 
1.1       albertel 1701: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1702: 
1.599     albertel 1703: my %homecache;
1.1       albertel 1704: sub homeserver {
1.230     stredwic 1705:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1706:     my $index="$uname:$udom";
1.426     albertel 1707: 
1.599     albertel 1708:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1709: 
                   1710:     my %servers = &get_servers($udom,'library');
                   1711:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1712:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1713: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1714: 
                   1715: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1716: 	if ($answer eq 'found') {
                   1717: 	    delete($badServerCache{$tryserver}); 
                   1718: 	    return $homecache{$index}=$tryserver;
                   1719: 	} elsif ($answer eq 'no_host') {
                   1720: 	    $badServerCache{$tryserver}=1;
                   1721: 	}
1.1       albertel 1722:     }    
                   1723:     return 'no_host';
1.70      www      1724: }
                   1725: 
                   1726: # ------------------------------------- Find the usernames behind a list of IDs
                   1727: 
                   1728: sub idget {
                   1729:     my ($udom,@ids)=@_;
                   1730:     my %returnhash=();
                   1731:     
1.841     albertel 1732:     my %servers = &get_servers($udom,'library');
                   1733:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1734: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1735: 	$idlist=~tr/A-Z/a-z/; 
                   1736: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1737: 	my @answer=();
                   1738: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1739: 	    @answer=split(/\&/,$reply);
                   1740: 	}                    ;
                   1741: 	my $i;
                   1742: 	for ($i=0;$i<=$#ids;$i++) {
                   1743: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1744: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1745: 	    } 
                   1746: 	}
                   1747:     } 
1.70      www      1748:     return %returnhash;
                   1749: }
                   1750: 
                   1751: # ------------------------------------- Find the IDs behind a list of usernames
                   1752: 
                   1753: sub idrget {
                   1754:     my ($udom,@unames)=@_;
                   1755:     my %returnhash=();
1.800     albertel 1756:     foreach my $uname (@unames) {
                   1757:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1758:     }
1.70      www      1759:     return %returnhash;
                   1760: }
                   1761: 
                   1762: # ------------------------------- Store away a list of names and associated IDs
                   1763: 
                   1764: sub idput {
                   1765:     my ($udom,%ids)=@_;
                   1766:     my %servers=();
1.800     albertel 1767:     foreach my $uname (keys(%ids)) {
                   1768: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1769:         my $uhom=&homeserver($uname,$udom);
1.70      www      1770:         if ($uhom ne 'no_host') {
1.800     albertel 1771:             my $id=&escape($ids{$uname});
1.70      www      1772:             $id=~tr/A-Z/a-z/;
1.800     albertel 1773:             my $esc_unam=&escape($uname);
1.70      www      1774: 	    if ($servers{$uhom}) {
1.800     albertel 1775: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1776:             } else {
1.800     albertel 1777:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1778:             }
                   1779:         }
1.191     harris41 1780:     }
1.800     albertel 1781:     foreach my $server (keys(%servers)) {
                   1782:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1783:     }
1.344     www      1784: }
                   1785: 
1.1172.2.30  raeburn  1786: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1787: 
                   1788: sub iddel {
                   1789:     my ($udom,$idshashref,$uhome)=@_;
                   1790:     my %result=();
                   1791:     unless (ref($idshashref) eq 'HASH') {
                   1792:         return %result;
                   1793:     }
                   1794:     my %servers=();
                   1795:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1796:         my $uhom;
                   1797:         if ($uhome) {
                   1798:             $uhom = $uhome;
                   1799:         } else {
                   1800:             $uhom=&homeserver($uname,$udom);
                   1801:         }
                   1802:         if ($uhom ne 'no_host') {
                   1803:             if ($servers{$uhom}) {
                   1804:                 $servers{$uhom}.='&'.&escape($id);
                   1805:             } else {
                   1806:                 $servers{$uhom}=&escape($id);
                   1807:             }
                   1808:         }
                   1809:     }
                   1810:     foreach my $server (keys(%servers)) {
                   1811:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1812:     }
                   1813:     return %result;
                   1814: }
                   1815: 
1.1023    raeburn  1816: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1817: sub dump_dom {
1.1165    droeschl 1818:     my ($namespace, $udom, $regexp) = @_;
                   1819: 
                   1820:     $udom ||= $env{'user.domain'};
                   1821: 
                   1822:     return () unless $udom;
                   1823: 
                   1824:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1825: }
                   1826: 
1.1023    raeburn  1827: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1828: 
                   1829: sub get_dom {
1.860     raeburn  1830:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1831:     return if ($udom eq 'public');
1.806     raeburn  1832:     my $items='';
                   1833:     foreach my $item (@$storearr) {
                   1834:         $items.=&escape($item).'&';
                   1835:     }
                   1836:     $items=~s/\&$//;
1.860     raeburn  1837:     if (!$udom) {
                   1838:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1839:         return if ($udom eq 'public');
1.860     raeburn  1840:         if (defined(&domain($udom,'primary'))) {
                   1841:             $uhome=&domain($udom,'primary');
                   1842:         } else {
1.874     albertel 1843:             undef($uhome);
1.860     raeburn  1844:         }
                   1845:     } else {
                   1846:         if (!$uhome) {
                   1847:             if (defined(&domain($udom,'primary'))) {
                   1848:                 $uhome=&domain($udom,'primary');
                   1849:             }
                   1850:         }
                   1851:     }
                   1852:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1853:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1854:         my %returnhash;
1.875     albertel 1855:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1856:             return %returnhash;
                   1857:         }
1.806     raeburn  1858:         my @pairs=split(/\&/,$rep);
                   1859:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1860:             return @pairs;
                   1861:         }
                   1862:         my $i=0;
                   1863:         foreach my $item (@$storearr) {
                   1864:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1865:             $i++;
                   1866:         }
                   1867:         return %returnhash;
                   1868:     } else {
1.880     banghart 1869:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1870:     }
                   1871: }
                   1872: 
                   1873: # -------------------------------------------- put items in domain db files 
                   1874: 
                   1875: sub put_dom {
1.860     raeburn  1876:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1877:     if (!$udom) {
                   1878:         $udom=$env{'user.domain'};
                   1879:         if (defined(&domain($udom,'primary'))) {
                   1880:             $uhome=&domain($udom,'primary');
                   1881:         } else {
1.874     albertel 1882:             undef($uhome);
1.860     raeburn  1883:         }
                   1884:     } else {
                   1885:         if (!$uhome) {
                   1886:             if (defined(&domain($udom,'primary'))) {
                   1887:                 $uhome=&domain($udom,'primary');
                   1888:             }
                   1889:         }
                   1890:     } 
                   1891:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1892:         my $items='';
                   1893:         foreach my $item (keys(%$storehash)) {
                   1894:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1895:         }
                   1896:         $items=~s/\&$//;
                   1897:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1898:     } else {
1.860     raeburn  1899:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1900:     }
                   1901: }
                   1902: 
1.1023    raeburn  1903: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1904: sub newput_dom {
1.1023    raeburn  1905:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1906:     my $result;
                   1907:     if (!$udom) {
                   1908:         $udom=$env{'user.domain'};
                   1909:     }
1.1023    raeburn  1910:     if ($udom) {
                   1911:         my $uname = &get_domainconfiguser($udom);
                   1912:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1913:     }
                   1914:     return $result;
                   1915: }
                   1916: 
1.1023    raeburn  1917: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1918: sub del_dom {
1.1023    raeburn  1919:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1920:     if (ref($storearr) eq 'ARRAY') {
                   1921:         if (!$udom) {
                   1922:             $udom=$env{'user.domain'};
                   1923:         }
1.1023    raeburn  1924:         if ($udom) {
                   1925:             my $uname = &get_domainconfiguser($udom); 
                   1926:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1927:         }
                   1928:     }
                   1929: }
                   1930: 
1.1023    raeburn  1931: # ----------------------------------construct domainconfig user for a domain 
                   1932: sub get_domainconfiguser {
                   1933:     my ($udom) = @_;
                   1934:     return $udom.'-domainconfig';
                   1935: }
                   1936: 
1.837     raeburn  1937: sub retrieve_inst_usertypes {
                   1938:     my ($udom) = @_;
                   1939:     my (%returnhash,@order);
1.989     raeburn  1940:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1941:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1942:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1943:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1944:     } else {
                   1945:         if (defined(&domain($udom,'primary'))) {
                   1946:             my $uhome=&domain($udom,'primary');
                   1947:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1948:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1949:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1950:                 return (\%returnhash,\@order);
                   1951:             }
                   1952:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1953:             my @pairs=split(/\&/,$hashitems);
                   1954:             foreach my $item (@pairs) {
                   1955:                 my ($key,$value)=split(/=/,$item,2);
                   1956:                 $key = &unescape($key);
                   1957:                 next if ($key =~ /^error: 2 /);
                   1958:                 $returnhash{$key}=&thaw_unescape($value);
                   1959:             }
                   1960:             my @esc_order = split(/\&/,$orderitems);
                   1961:             foreach my $item (@esc_order) {
                   1962:                 push(@order,&unescape($item));
                   1963:             }
                   1964:         } else {
1.1172.2.44  raeburn  1965:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1966:         }
1.1172.2.44  raeburn  1967:         return (\%returnhash,\@order);
1.837     raeburn  1968:     }
                   1969: }
                   1970: 
1.868     raeburn  1971: sub is_domainimage {
                   1972:     my ($url) = @_;
1.1172.2.74  raeburn  1973:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1974:         if (&domain($1) ne '') {
                   1975:             return '1';
                   1976:         }
                   1977:     }
                   1978:     return;
                   1979: }
                   1980: 
1.899     raeburn  1981: sub inst_directory_query {
                   1982:     my ($srch) = @_;
                   1983:     my $udom = $srch->{'srchdomain'};
                   1984:     my %results;
                   1985:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1986:     my $outcome;
1.899     raeburn  1987:     if ($homeserver ne '') {
1.904     albertel 1988: 	my $queryid=&reply("querysend:instdirsearch:".
                   1989: 			   &escape($srch->{'srchby'}).':'.
                   1990: 			   &escape($srch->{'srchterm'}).':'.
                   1991: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1992: 	my $host=&hostname($homeserver);
                   1993: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1994: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1995: 	    return;
                   1996: 	}
                   1997: 	my $response = &get_query_reply($queryid);
                   1998: 	my $maxtries = 5;
                   1999: 	my $tries = 1;
                   2000: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2001: 	    $response = &get_query_reply($queryid);
                   2002: 	    $tries ++;
                   2003: 	}
                   2004: 
                   2005:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2006:             if ($response eq 'unavailable') {
                   2007:                 $outcome = $response;
                   2008:             } else {
                   2009:                 $outcome = 'ok';
                   2010:                 my @matches = split(/\n/,$response);
                   2011:                 foreach my $match (@matches) {
                   2012:                     my ($key,$value) = split(/=/,$match);
                   2013:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2014:                 }
1.899     raeburn  2015:             }
                   2016:         }
                   2017:     }
1.909     raeburn  2018:     return ($outcome,%results);
1.899     raeburn  2019: }
                   2020: 
                   2021: sub usersearch {
                   2022:     my ($srch) = @_;
                   2023:     my $dom = $srch->{'srchdomain'};
                   2024:     my %results;
                   2025:     my %libserv = &all_library();
                   2026:     my $query = 'usersearch';
                   2027:     foreach my $tryserver (keys(%libserv)) {
                   2028:         if (&host_domain($tryserver) eq $dom) {
                   2029:             my $host=&hostname($tryserver);
                   2030:             my $queryid=
1.911     raeburn  2031:                 &reply("querysend:".&escape($query).':'.
                   2032:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2033:                        &escape($srch->{'srchtype'}).':'.
                   2034:                        &escape($srch->{'srchterm'}),$tryserver);
                   2035:             if ($queryid !~/^\Q$host\E\_/) {
                   2036:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2037:                 next;
1.899     raeburn  2038:             }
                   2039:             my $reply = &get_query_reply($queryid);
                   2040:             my $maxtries = 1;
                   2041:             my $tries = 1;
                   2042:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2043:                 $reply = &get_query_reply($queryid);
                   2044:                 $tries ++;
                   2045:             }
                   2046:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2047:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2048:             } else {
1.911     raeburn  2049:                 my @matches;
                   2050:                 if ($reply =~ /\n/) {
                   2051:                     @matches = split(/\n/,$reply);
                   2052:                 } else {
                   2053:                     @matches = split(/\&/,$reply);
                   2054:                 }
1.899     raeburn  2055:                 foreach my $match (@matches) {
                   2056:                     my ($uname,$udom,%userhash);
1.911     raeburn  2057:                     foreach my $entry (split(/:/,$match)) {
                   2058:                         my ($key,$value) =
                   2059:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2060:                         $userhash{$key} = $value;
                   2061:                         if ($key eq 'username') {
                   2062:                             $uname = $value;
                   2063:                         } elsif ($key eq 'domain') {
                   2064:                             $udom = $value;
1.911     raeburn  2065:                         }
1.899     raeburn  2066:                     }
                   2067:                     $results{$uname.':'.$udom} = \%userhash;
                   2068:                 }
                   2069:             }
                   2070:         }
                   2071:     }
                   2072:     return %results;
                   2073: }
                   2074: 
1.912     raeburn  2075: sub get_instuser {
                   2076:     my ($udom,$uname,$id) = @_;
                   2077:     my $homeserver = &domain($udom,'primary');
                   2078:     my ($outcome,%results);
                   2079:     if ($homeserver ne '') {
                   2080:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2081:                            &escape($id).':'.&escape($udom),$homeserver);
                   2082:         my $host=&hostname($homeserver);
                   2083:         if ($queryid !~/^\Q$host\E\_/) {
                   2084:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2085:             return;
                   2086:         }
                   2087:         my $response = &get_query_reply($queryid);
                   2088:         my $maxtries = 5;
                   2089:         my $tries = 1;
                   2090:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2091:             $response = &get_query_reply($queryid);
                   2092:             $tries ++;
                   2093:         }
                   2094:         if (!&error($response) && $response ne 'refused') {
                   2095:             if ($response eq 'unavailable') {
                   2096:                 $outcome = $response;
                   2097:             } else {
                   2098:                 $outcome = 'ok';
                   2099:                 my @matches = split(/\n/,$response);
                   2100:                 foreach my $match (@matches) {
                   2101:                     my ($key,$value) = split(/=/,$match);
                   2102:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2103:                 }
                   2104:             }
                   2105:         }
                   2106:     }
                   2107:     my %userinfo;
                   2108:     if (ref($results{$uname}) eq 'HASH') {
                   2109:         %userinfo = %{$results{$uname}};
                   2110:     } 
                   2111:     return ($outcome,%userinfo);
                   2112: }
                   2113: 
1.1172.2.69  raeburn  2114: sub get_multiple_instusers {
                   2115:     my ($udom,$users,$caller) = @_;
                   2116:     my ($outcome,$results);
                   2117:     if (ref($users) eq 'HASH') {
                   2118:         my $count = keys(%{$users});
                   2119:         my $requested = &freeze_escape($users);
                   2120:         my $homeserver = &domain($udom,'primary');
                   2121:         if ($homeserver ne '') {
                   2122:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2123:             my $host=&hostname($homeserver);
                   2124:             if ($queryid !~/^\Q$host\E\_/) {
                   2125:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2126:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2127:                 return ($outcome,$results);
                   2128:             }
                   2129:             my $response = &get_query_reply($queryid);
                   2130:             my $maxtries = 5;
                   2131:             if ($count > 100) {
                   2132:                 $maxtries = 1+int($count/20);
                   2133:             }
                   2134:             my $tries = 1;
                   2135:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2136:                 $response = &get_query_reply($queryid);
                   2137:                 $tries ++;
                   2138:             }
                   2139:             if ($response eq '') {
                   2140:                 $results = {};
                   2141:                 foreach my $key (keys(%{$users})) {
                   2142:                     my ($uname,$id);
                   2143:                     if ($caller eq 'id') {
                   2144:                         $id = $key;
                   2145:                     } else {
                   2146:                         $uname = $key;
                   2147:                     }
                   2148:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2149:                     $outcome = $resp;
                   2150:                     if ($resp eq 'ok') {
                   2151:                         %{$results} = (%{$results}, %info);
                   2152:                     } else {
                   2153:                         last;
                   2154:                     }
                   2155:                 }
                   2156:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2157:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2158:                     $outcome = $response;
                   2159:                 } else {
                   2160:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2161:                     if ($outcome eq 'ok') {
                   2162:                         $results = &thaw_unescape($userdata);
                   2163:                     }
                   2164:                 }
                   2165:             }
                   2166:         }
                   2167:     }
                   2168:     return ($outcome,$results);
                   2169: }
                   2170: 
1.912     raeburn  2171: sub inst_rulecheck {
1.923     raeburn  2172:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2173:     my %returnhash;
                   2174:     if ($udom ne '') {
                   2175:         if (ref($rules) eq 'ARRAY') {
                   2176:             @{$rules} = map {&escape($_);} (@{$rules});
                   2177:             my $rulestr = join(':',@{$rules});
                   2178:             my $homeserver=&domain($udom,'primary');
                   2179:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2180:                 my $response;
                   2181:                 if ($item eq 'username') {                
                   2182:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2183:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2184:                                               $homeserver));
1.923     raeburn  2185:                 } elsif ($item eq 'id') {
                   2186:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2187:                                               ':'.&escape($id).':'.$rulestr,
                   2188:                                               $homeserver));
1.945     raeburn  2189:                 } elsif ($item eq 'selfcreate') {
                   2190:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2191:                                                &escape($udom).':'.&escape($uname).
                   2192:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2193:                 }
1.912     raeburn  2194:                 if ($response ne 'refused') {
                   2195:                     my @pairs=split(/\&/,$response);
                   2196:                     foreach my $item (@pairs) {
                   2197:                         my ($key,$value)=split(/=/,$item,2);
                   2198:                         $key = &unescape($key);
                   2199:                         next if ($key =~ /^error: 2 /);
                   2200:                         $returnhash{$key}=&thaw_unescape($value);
                   2201:                     }
                   2202:                 }
                   2203:             }
                   2204:         }
                   2205:     }
                   2206:     return %returnhash;
                   2207: }
                   2208: 
                   2209: sub inst_userrules {
1.923     raeburn  2210:     my ($udom,$check) = @_;
1.912     raeburn  2211:     my (%ruleshash,@ruleorder);
                   2212:     if ($udom ne '') {
                   2213:         my $homeserver=&domain($udom,'primary');
                   2214:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2215:             my $response;
                   2216:             if ($check eq 'id') {
                   2217:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2218:                                  $homeserver);
1.943     raeburn  2219:             } elsif ($check eq 'email') {
                   2220:                 $response=&reply('instemailrules:'.&escape($udom),
                   2221:                                  $homeserver);
1.923     raeburn  2222:             } else {
                   2223:                 $response=&reply('instuserrules:'.&escape($udom),
                   2224:                                  $homeserver);
                   2225:             }
1.912     raeburn  2226:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2227:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2228:                 ($response ne 'no_such_host')) {
                   2229:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2230:                 my @pairs=split(/\&/,$hashitems);
                   2231:                 foreach my $item (@pairs) {
                   2232:                     my ($key,$value)=split(/=/,$item,2);
                   2233:                     $key = &unescape($key);
                   2234:                     next if ($key =~ /^error: 2 /);
                   2235:                     $ruleshash{$key}=&thaw_unescape($value);
                   2236:                 }
                   2237:                 my @esc_order = split(/\&/,$orderitems);
                   2238:                 foreach my $item (@esc_order) {
                   2239:                     push(@ruleorder,&unescape($item));
                   2240:                 }
                   2241:             }
                   2242:         }
                   2243:     }
                   2244:     return (\%ruleshash,\@ruleorder);
                   2245: }
                   2246: 
1.976     raeburn  2247: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2248: 
                   2249: sub get_domain_defaults {
1.1172.2.35  raeburn  2250:     my ($domain,$ignore_cache) = @_;
                   2251:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2252:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2253:     unless ($ignore_cache) {
                   2254:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2255:         if (defined($cached)) {
                   2256:             if (ref($result) eq 'HASH') {
                   2257:                 return %{$result};
                   2258:             }
1.943     raeburn  2259:         }
                   2260:     }
                   2261:     my %domdefaults;
                   2262:     my %domconfig =
1.989     raeburn  2263:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2264:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2265:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2266:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2267:                                   'coursecategories','autoenroll',
                   2268:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2269:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2270:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2271:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2272:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2273:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2274:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2275:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2276:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2277:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2278:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2279:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2280:     } else {
                   2281:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2282:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2283:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2284:     }
1.976     raeburn  2285:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2286:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2287:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2288:         } else {
                   2289:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2290:         }
1.1172.2.6  raeburn  2291:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2292:         foreach my $item (@usertools) {
                   2293:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2294:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2295:             }
                   2296:         }
1.1172.2.29  raeburn  2297:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2298:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2299:         }
1.976     raeburn  2300:     }
1.985     raeburn  2301:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2302:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2303:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2304:         }
                   2305:     }
1.1172.2.9  raeburn  2306:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2307:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2308:     }
1.989     raeburn  2309:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2310:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2311:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2312:         }
                   2313:     }
1.1047    raeburn  2314:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2315:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2316:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2317:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2318:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2319:         }
1.1172.2.41  raeburn  2320:         foreach my $type (@coursetypes) {
                   2321:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2322:                 unless ($type eq 'community') {
                   2323:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2324:                 }
                   2325:             }
                   2326:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2327:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2328:             }
1.1172.2.60  raeburn  2329:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2330:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2331:                     $domdefaults{$type.'postsubtimeout'} =
                   2332:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2333:                 }
                   2334:             }
1.1172.2.30  raeburn  2335:         }
1.1172.2.67  raeburn  2336:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2337:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2338:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2339:                 if (@clonecodes) {
                   2340:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2341:                 }
                   2342:             }
                   2343:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2344:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2345:         }
1.1172.2.103  raeburn  2346:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2347:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2348:         }
1.1047    raeburn  2349:     }
1.1073    raeburn  2350:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2351:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2352:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2353:         }
                   2354:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2355:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2356:         }
1.1172.2.62  raeburn  2357:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2358:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2359:         }
1.1073    raeburn  2360:     }
1.1172.2.41  raeburn  2361:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2362:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2363:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2364:                             'approval','limit');
                   2365:             foreach my $type (@coursetypes) {
                   2366:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2367:                     my @mgrdc = ();
                   2368:                     foreach my $item (@settings) {
                   2369:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2370:                             push(@mgrdc,$item);
                   2371:                         }
                   2372:                     }
                   2373:                     if (@mgrdc) {
                   2374:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2375:                     }
                   2376:                 }
                   2377:             }
                   2378:         }
                   2379:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2380:             foreach my $type (@coursetypes) {
                   2381:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2382:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2383:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2384:                     }
                   2385:                 }
                   2386:             }
                   2387:         }
                   2388:     }
1.1172.2.46  raeburn  2389:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2390:         $domdefaults{'catauth'} = 'std';
                   2391:         $domdefaults{'catunauth'} = 'std';
                   2392:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2393:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2394:         }
                   2395:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2396:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2397:         }
                   2398:     }
1.1172.2.76  raeburn  2399:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2400:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2401:     }
1.1172.2.89  raeburn  2402:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2403:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2404:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2405:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2406:         }
                   2407:     }
1.1172.2.23  raeburn  2408:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2409:     return %domdefaults;
                   2410: }
                   2411: 
1.1172.2.106  raeburn  2412: sub get_dom_cats {
                   2413:     my ($dom) = @_;
                   2414:     return unless (&domain($dom));
                   2415:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2416:     unless (defined($cached)) {
                   2417:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2418:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2419:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2420:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2421:             } else {
                   2422:                 $cats = {};
                   2423:             }
                   2424:         } else {
                   2425:             $cats = {};
                   2426:         }
                   2427:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2428:     }
                   2429:     return $cats;
                   2430: }
                   2431: 
                   2432: sub get_dom_instcats {
                   2433:     my ($dom) = @_;
                   2434:     return unless (&domain($dom));
                   2435:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2436:     unless (defined($cached)) {
                   2437:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2438:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2439:         if ($totcodes > 0) {
                   2440:             my $caller = 'global';
                   2441:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2442:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2443:                 $instcats = {
                   2444:                                 codes => \%codes,
                   2445:                                 codetitles => \@codetitles,
                   2446:                                 cat_titles => \%cat_titles,
                   2447:                                 cat_order => \%cat_order,
                   2448:                             };
                   2449:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2450:             }
                   2451:         }
                   2452:     }
                   2453:     return $instcats;
                   2454: }
                   2455: 
                   2456: sub retrieve_instcodes {
                   2457:     my ($coursecodes,$dom) = @_;
                   2458:     my $totcodes;
                   2459:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2460:     foreach my $course (keys(%courses)) {
                   2461:         if (ref($courses{$course}) eq 'HASH') {
                   2462:             if ($courses{$course}{'inst_code'} ne '') {
                   2463:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2464:                 $totcodes ++;
                   2465:             }
                   2466:         }
                   2467:     }
                   2468:     return $totcodes;
                   2469: }
                   2470: 
1.1172.2.113  raeburn  2471: # --------------------------------------------- Get domain config for passwords
                   2472: 
                   2473: sub get_passwdconf {
                   2474:     my ($dom) = @_;
                   2475:     my (%passwdconf,$gotconf,$lookup);
                   2476:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2477:     if (defined($cached)) {
                   2478:         if (ref($result) eq 'HASH') {
                   2479:             %passwdconf = %{$result};
                   2480:             $gotconf = 1;
                   2481:         }
                   2482:     }
                   2483:     unless ($gotconf) {
                   2484:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2485:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2486:             %passwdconf = %{$domconfig{'passwords'}};
                   2487:         }
                   2488:         my $cachetime = 24*60*60;
                   2489:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2490:     }
                   2491:     return %passwdconf;
                   2492: }
                   2493: 
1.344     www      2494: # --------------------------------------------------- Assign a key to a student
                   2495: 
                   2496: sub assign_access_key {
1.364     www      2497: #
                   2498: # a valid key looks like uname:udom#comments
                   2499: # comments are being appended
                   2500: #
1.498     www      2501:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2502:     $kdom=
1.620     albertel 2503:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2504:     $knum=
1.620     albertel 2505:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2506:     $cdom=
1.620     albertel 2507:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2508:     $cnum=
1.620     albertel 2509:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2510:     $udom=$env{'user.name'} unless (defined($udom));
                   2511:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2512:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2513:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2514:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2515:                                                   # assigned to this person
                   2516:                                                   # - this should not happen,
1.345     www      2517:                                                   # unless something went wrong
                   2518:                                                   # the first time around
                   2519: # ready to assign
1.364     www      2520:         $logentry=$1.'; '.$logentry;
1.496     www      2521:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2522:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2523: # key now belongs to user
1.346     www      2524: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2525:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2526:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2527:                 return 'ok';
                   2528:             } else {
                   2529:                 return 
                   2530:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2531: 	    }
                   2532:         } else {
                   2533:             return 'error: Could not assign key, try again later.';
                   2534:         }
1.364     www      2535:     } elsif (!$existing{$ckey}) {
1.345     www      2536: # the key does not exist
                   2537: 	return 'error: The key does not exist';
                   2538:     } else {
                   2539: # the key is somebody else's
                   2540: 	return 'error: The key is already in use';
                   2541:     }
1.344     www      2542: }
                   2543: 
1.364     www      2544: # ------------------------------------------ put an additional comment on a key
                   2545: 
                   2546: sub comment_access_key {
                   2547: #
                   2548: # a valid key looks like uname:udom#comments
                   2549: # comments are being appended
                   2550: #
                   2551:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2552:     $cdom=
1.620     albertel 2553:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2554:     $cnum=
1.620     albertel 2555:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2556:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2557:     if ($existing{$ckey}) {
                   2558:         $existing{$ckey}.='; '.$logentry;
                   2559: # ready to assign
1.367     www      2560:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2561:                                                  $cdom,$cnum) eq 'ok') {
                   2562: 	    return 'ok';
                   2563:         } else {
                   2564: 	    return 'error: Count not store comment.';
                   2565:         }
                   2566:     } else {
                   2567: # the key does not exist
                   2568: 	return 'error: The key does not exist';
                   2569:     }
                   2570: }
                   2571: 
1.344     www      2572: # ------------------------------------------------------ Generate a set of keys
                   2573: 
                   2574: sub generate_access_keys {
1.364     www      2575:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2576:     $cdom=
1.620     albertel 2577:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2578:     $cnum=
1.620     albertel 2579:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2580:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2581:     unless (($cdom) && ($cnum)) { return 0; }
                   2582:     if ($number>10000) { return 0; }
                   2583:     sleep(2); # make sure don't get same seed twice
                   2584:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2585:     my $total=0;
                   2586:     for (my $i=1;$i<=$number;$i++) {
                   2587:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2588:                   sprintf("%lx",int(100000*rand)).'-'.
                   2589:                   sprintf("%lx",int(100000*rand));
                   2590:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2591:        $newkey=~s/0/h/g; # and also 0 and O
                   2592:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2593:        if ($existing{$newkey}) {
                   2594:            $i--;
                   2595:        } else {
1.364     www      2596: 	  if (&put('accesskeys',
                   2597:               { $newkey => '# generated '.localtime().
1.620     albertel 2598:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2599:                            '; '.$logentry },
                   2600: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2601:               $total++;
                   2602: 	  }
                   2603:        }
                   2604:     }
1.620     albertel 2605:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2606:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2607:     return $total;
                   2608: }
                   2609: 
                   2610: # ------------------------------------------------------- Validate an accesskey
                   2611: 
                   2612: sub validate_access_key {
                   2613:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2614:     $cdom=
1.620     albertel 2615:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2616:     $cnum=
1.620     albertel 2617:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2618:     $udom=$env{'user.domain'} unless (defined($udom));
                   2619:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2620:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2621:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2622: }
                   2623: 
                   2624: # ------------------------------------- Find the section of student in a course
1.652     albertel 2625: sub devalidate_getsection_cache {
                   2626:     my ($udom,$unam,$courseid)=@_;
                   2627:     my $hashid="$udom:$unam:$courseid";
                   2628:     &devalidate_cache_new('getsection',$hashid);
                   2629: }
1.298     matthew  2630: 
1.815     albertel 2631: sub courseid_to_courseurl {
                   2632:     my ($courseid) = @_;
                   2633:     #already url style courseid
                   2634:     return $courseid if ($courseid =~ m{^/});
                   2635: 
                   2636:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2637: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2638: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2639: 	return "/$cdom/$cnum";
                   2640:     }
                   2641: 
                   2642:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2643:     if (exists($courseinfo{'num'})) {
                   2644: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2645:     }
                   2646: 
                   2647:     return undef;
                   2648: }
                   2649: 
1.298     matthew  2650: sub getsection {
                   2651:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2652:     my $cachetime=1800;
1.551     albertel 2653: 
                   2654:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2655:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2656:     if (defined($cached)) { return $result; }
                   2657: 
1.298     matthew  2658:     my %Pending; 
                   2659:     my %Expired;
                   2660:     #
                   2661:     # Each role can either have not started yet (pending), be active, 
                   2662:     #    or have expired.
                   2663:     #
                   2664:     # If there is an active role, we are done.
                   2665:     #
                   2666:     # If there is more than one role which has not started yet, 
                   2667:     #     choose the one which will start sooner
                   2668:     # If there is one role which has not started yet, return it.
                   2669:     #
                   2670:     # If there is more than one expired role, choose the one which ended last.
                   2671:     # If there is a role which has expired, return it.
                   2672:     #
1.815     albertel 2673:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2674:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2675:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2676:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2677:         my $section=$1;
                   2678:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2679:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2680:         my $now=time;
1.548     albertel 2681:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2682:             $Expired{$end}=$section;
                   2683:             next;
                   2684:         }
1.548     albertel 2685:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2686:             $Pending{$start}=$section;
                   2687:             next;
                   2688:         }
1.599     albertel 2689:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2690:     }
                   2691:     #
                   2692:     # Presumedly there will be few matching roles from the above
                   2693:     # loop and the sorting time will be negligible.
                   2694:     if (scalar(keys(%Pending))) {
                   2695:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2696:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2697:     } 
                   2698:     if (scalar(keys(%Expired))) {
                   2699:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2700:         my $time = pop(@sorted);
1.599     albertel 2701:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2702:     }
1.599     albertel 2703:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2704: }
1.70      www      2705: 
1.599     albertel 2706: sub save_cache {
                   2707:     &purge_remembered();
1.722     albertel 2708:     #&Apache::loncommon::validate_page();
1.620     albertel 2709:     undef(%env);
1.780     albertel 2710:     undef($env_loaded);
1.599     albertel 2711: }
1.452     albertel 2712: 
1.599     albertel 2713: my $to_remember=-1;
                   2714: my %remembered;
                   2715: my %accessed;
                   2716: my $kicks=0;
                   2717: my $hits=0;
1.849     albertel 2718: sub make_key {
                   2719:     my ($name,$id) = @_;
1.872     albertel 2720:     if (length($id) > 65 
                   2721: 	&& length(&escape($id)) > 200) {
                   2722: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2723:     }
1.849     albertel 2724:     return &escape($name.':'.$id);
                   2725: }
                   2726: 
1.599     albertel 2727: sub devalidate_cache_new {
                   2728:     my ($name,$id,$debug) = @_;
                   2729:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2730:     my $remembered_id=$name.':'.$id;
1.849     albertel 2731:     $id=&make_key($name,$id);
1.599     albertel 2732:     $memcache->delete($id);
1.1172.2.81  raeburn  2733:     delete($remembered{$remembered_id});
                   2734:     delete($accessed{$remembered_id});
1.599     albertel 2735: }
                   2736: 
                   2737: sub is_cached_new {
                   2738:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2739:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2740:                                      # keys in %remembered hash, which persists for
                   2741:                                      # duration of request (no restriction on key length).
                   2742:     if (exists($remembered{$remembered_id})) {
                   2743: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2744: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2745: 	$hits++;
1.1172.2.81  raeburn  2746: 	return ($remembered{$remembered_id},1);
1.599     albertel 2747:     }
1.1172.2.81  raeburn  2748:     $id=&make_key($name,$id);
1.599     albertel 2749:     my $value = $memcache->get($id);
                   2750:     if (!(defined($value))) {
                   2751: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2752: 	return (undef,undef);
1.416     albertel 2753:     }
1.599     albertel 2754:     if ($value eq '__undef__') {
                   2755: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2756: 	$value=undef;
                   2757:     }
1.1172.2.81  raeburn  2758:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2759:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2760:     return ($value,1);
                   2761: }
                   2762: 
                   2763: sub do_cache_new {
                   2764:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2765:     my $remembered_id=$name.':'.$id;
1.849     albertel 2766:     $id=&make_key($name,$id);
1.599     albertel 2767:     my $setvalue=$value;
                   2768:     if (!defined($setvalue)) {
                   2769: 	$setvalue='__undef__';
                   2770:     }
1.623     albertel 2771:     if (!defined($time) ) {
                   2772: 	$time=600;
                   2773:     }
1.599     albertel 2774:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2775:     my $result = $memcache->set($id,$setvalue,$time);
                   2776:     if (! $result) {
1.872     albertel 2777: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2778: 	$memcache->disconnect_all();
1.872     albertel 2779:     }
1.600     albertel 2780:     # need to make a copy of $value
1.1172.2.81  raeburn  2781:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2782:     return $value;
                   2783: }
                   2784: 
                   2785: sub make_room {
1.1172.2.81  raeburn  2786:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2787: 
1.1172.2.81  raeburn  2788:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2789:                                     : $value;
1.599     albertel 2790:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2791:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2792:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2793:     my $to_kick;
                   2794:     my $max_time=0;
                   2795:     foreach my $other (keys(%accessed)) {
                   2796: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2797: 	    $to_kick=$other;
                   2798: 	    $max_time=&tv_interval($accessed{$other});
                   2799: 	}
                   2800:     }
                   2801:     delete($remembered{$to_kick});
                   2802:     delete($accessed{$to_kick});
                   2803:     $kicks++;
                   2804:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2805:     return;
                   2806: }
                   2807: 
1.599     albertel 2808: sub purge_remembered {
1.604     albertel 2809:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2810:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2811:     undef(%remembered);
                   2812:     undef(%accessed);
1.428     albertel 2813: }
1.70      www      2814: # ------------------------------------- Read an entry from a user's environment
                   2815: 
                   2816: sub userenvironment {
                   2817:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2818:     my $items;
                   2819:     foreach my $item (@what) {
                   2820:         $items.=&escape($item).'&';
                   2821:     }
                   2822:     $items=~s/\&$//;
1.70      www      2823:     my %returnhash=();
1.1009    raeburn  2824:     my $uhome = &homeserver($unam,$udom);
                   2825:     unless ($uhome eq 'no_host') {
                   2826:         my @answer=split(/\&/, 
                   2827:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2828:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2829:             return %returnhash;
                   2830:         }
1.1009    raeburn  2831:         my $i;
                   2832:         for ($i=0;$i<=$#what;$i++) {
                   2833: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2834:         }
1.70      www      2835:     }
                   2836:     return %returnhash;
1.1       albertel 2837: }
                   2838: 
1.617     albertel 2839: # ---------------------------------------------------------- Get a studentphoto
                   2840: sub studentphoto {
                   2841:     my ($udom,$unam,$ext) = @_;
                   2842:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2843:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2844:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2845:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2846:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2847:             } else {
                   2848:                 my ($result,$perm_reqd)=
1.707     albertel 2849: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2850:                 if ($result eq 'ok') {
                   2851:                     if (!($perm_reqd eq 'yes')) {
                   2852:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2853:                     }
                   2854:                 }
                   2855:             }
                   2856:         }
                   2857:     } else {
                   2858:         my ($result,$perm_reqd) = 
1.707     albertel 2859: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2860:         if ($result eq 'ok') {
                   2861:             if (!($perm_reqd eq 'yes')) {
                   2862:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2863:             }
                   2864:         }
                   2865:     }
                   2866:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2867: }
                   2868: 
                   2869: sub retrievestudentphoto {
                   2870:     my ($udom,$unam,$ext,$type) = @_;
                   2871:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2872:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2873:     if ($ret eq 'ok') {
                   2874:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2875:         if ($type eq 'thumbnail') {
                   2876:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2877:         }
                   2878:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2879:         return $tokenurl;
                   2880:     } else {
                   2881:         if ($type eq 'thumbnail') {
                   2882:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2883:         } else { 
                   2884:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2885:         }
1.617     albertel 2886:     }
                   2887: }
                   2888: 
1.263     www      2889: # -------------------------------------------------------------------- New chat
                   2890: 
                   2891: sub chatsend {
1.724     raeburn  2892:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2893:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2894:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2895:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2896:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2897: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2898: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2899: }
                   2900: 
                   2901: # ------------------------------------------ Find current version of a resource
                   2902: 
                   2903: sub getversion {
                   2904:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2905:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2906:     return &currentversion(&filelocation('',$fname));
                   2907: }
                   2908: 
                   2909: sub currentversion {
                   2910:     my $fname=shift;
                   2911:     my $author=$fname;
                   2912:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2913:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2914:     my $home=&homeserver($uname,$udom);
1.292     www      2915:     if ($home eq 'no_host') { 
                   2916:         return -1; 
                   2917:     }
1.1112    www      2918:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2919:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2920: 	return -1;
                   2921:     }
1.1112    www      2922:     return $answer;
1.263     www      2923: }
                   2924: 
1.1111    www      2925: #
                   2926: # Return special version number of resource if set by override, empty otherwise
                   2927: #
                   2928: sub usedversion {
                   2929:     my $fname=shift;
                   2930:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2931:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2932:     if ($urlversion) { return $urlversion; }
                   2933:     return '';
                   2934: }
                   2935: 
1.1       albertel 2936: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2937: 
1.1       albertel 2938: sub subscribe {
                   2939:     my $fname=shift;
1.761     raeburn  2940:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2941:     $fname=~s/[\n\r]//g;
1.1       albertel 2942:     my $author=$fname;
                   2943:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2944:     my ($udom,$uname)=split(/\//,$author);
                   2945:     my $home=homeserver($uname,$udom);
1.335     albertel 2946:     if ($home eq 'no_host') {
                   2947:         return 'not_found';
1.1       albertel 2948:     }
                   2949:     my $answer=reply("sub:$fname",$home);
1.64      www      2950:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2951: 	$answer.=' by '.$home;
                   2952:     }
1.1       albertel 2953:     return $answer;
                   2954: }
                   2955:     
1.8       www      2956: # -------------------------------------------------------------- Replicate file
                   2957: 
                   2958: sub repcopy {
                   2959:     my $filename=shift;
1.23      www      2960:     $filename=~s/\/+/\//g;
1.1142    raeburn  2961:     my $londocroot = $perlvar{'lonDocRoot'};
                   2962:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2963:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2964:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2965: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2966: 	return &repcopy_userfile($filename);
                   2967:     }
1.532     albertel 2968:     $filename=~s/[\n\r]//g;
1.8       www      2969:     my $transname="$filename.in.transfer";
1.828     www      2970: # FIXME: this should flock
1.607     raeburn  2971:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2972:     my $remoteurl=subscribe($filename);
1.64      www      2973:     if ($remoteurl =~ /^con_lost by/) {
                   2974: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2975:            return 'unavailable';
1.8       www      2976:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2977: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2978: 	   return 'not_found';
1.64      www      2979:     } elsif ($remoteurl =~ /^rejected by/) {
                   2980: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2981:            return 'forbidden';
1.20      www      2982:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2983:            return 'ok';
1.8       www      2984:     } else {
1.290     www      2985:         my $author=$filename;
                   2986:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2987:         my ($udom,$uname)=split(/\//,$author);
                   2988:         my $home=homeserver($uname,$udom);
                   2989:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2990:            my @parts=split(/\//,$filename);
                   2991:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2992:            if ($path ne "$londocroot/res") {
1.8       www      2993:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2994: 	       return 'bad_request';
1.8       www      2995:            }
                   2996:            my $count;
                   2997:            for ($count=5;$count<$#parts;$count++) {
                   2998:                $path.="/$parts[$count]";
                   2999:                if ((-e $path)!=1) {
                   3000: 		   mkdir($path,0777);
                   3001:                }
                   3002:            }
                   3003:            my $ua=new LWP::UserAgent;
                   3004:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3005:            my $response=$ua->request($request,$transname);
                   3006:            if ($response->is_error()) {
                   3007: 	       unlink($transname);
                   3008:                my $message=$response->status_line;
1.672     albertel 3009:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3010:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3011:                return 'unavailable';
1.8       www      3012:            } else {
1.16      www      3013: 	       if ($remoteurl!~/\.meta$/) {
                   3014:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3015:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3016:                   if ($mresponse->is_error()) {
                   3017: 		      unlink($filename.'.meta');
                   3018:                       &logthis(
1.672     albertel 3019:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3020:                   }
                   3021: 	       }
1.8       www      3022:                rename($transname,$filename);
1.607     raeburn  3023:                return 'ok';
1.8       www      3024:            }
1.290     www      3025:        }
1.8       www      3026:     }
1.330     www      3027: }
                   3028: 
                   3029: # ------------------------------------------------ Get server side include body
                   3030: sub ssi_body {
1.381     albertel 3031:     my ($filelink,%form)=@_;
1.606     matthew  3032:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3033:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3034:     }
1.953     www      3035:     my $output='';
                   3036:     my $response;
1.980     raeburn  3037:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3038:        ($output,$response)=&externalssi($filelink);
1.953     www      3039:     } else {
1.1004    droeschl 3040:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3041:        $filelink .= 'inhibitmenu=yes';
1.953     www      3042:        ($output,$response)=&ssi($filelink,%form);
                   3043:     }
1.778     albertel 3044:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3045:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3046:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3047:     if (wantarray) {
                   3048:         return ($output, $response);
                   3049:     } else {
                   3050:         return $output;
                   3051:     }
1.8       www      3052: }
                   3053: 
1.15      www      3054: # --------------------------------------------------------- Server Side Include
                   3055: 
1.782     albertel 3056: sub absolute_url {
                   3057:     my ($host_name) = @_;
                   3058:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3059:     if ($host_name eq '') {
                   3060: 	$host_name = $ENV{'SERVER_NAME'};
                   3061:     }
                   3062:     return $protocol.$host_name;
                   3063: }
                   3064: 
1.942     foxr     3065: #
                   3066: #   Server side include.
                   3067: # Parameters:
                   3068: #  fn     Possibly encrypted resource name/id.
                   3069: #  form   Hash that describes how the rendering should be done
                   3070: #         and other things.
1.944     foxr     3071: # Returns:
1.950     raeburn  3072: #   Scalar context: The content of the response.
                   3073: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3074: #     
1.15      www      3075: sub ssi {
                   3076: 
1.944     foxr     3077:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3078:     my ($request,$response);
1.711     albertel 3079: 
                   3080:     $form{'no_update_last_known'}=1;
1.895     albertel 3081:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3082:     if (%form) {
1.782     albertel 3083:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3084:       $request->content(join('&',map {
                   3085:             my $name = escape($_);
                   3086:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3087:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3088:             : &escape($form{$_}) );
                   3089:         } keys(%form)));
1.23      www      3090:     } else {
1.782     albertel 3091:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3092:     }
                   3093: 
1.15      www      3094:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3095: 
1.1172.2.101  raeburn  3096:     if (($env{'request.course.id'}) &&
                   3097:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3098:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3099:         ($form{'grade_symb'} ne '') &&
                   3100:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3101:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3102:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3103:             my $ua=new LWP::UserAgent;
                   3104:             $ua->local_address('127.0.0.1');
                   3105:             $response = $ua->request($request);
                   3106:         } else {
                   3107:             {
                   3108:                 require LWP::Protocol::http;
                   3109:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3110:                 my $ua=new LWP::UserAgent;
                   3111:                 $response = $ua->request($request);
                   3112:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3113:             }
                   3114:         }
                   3115:     } else {
                   3116:         my $ua=new LWP::UserAgent;
                   3117:         $response = $ua->request($request);
                   3118:     }
1.944     foxr     3119:     if (wantarray) {
1.1172.2.3  raeburn  3120: 	return ($response->content, $response);
1.944     foxr     3121:     } else {
1.1172.2.3  raeburn  3122: 	return $response->content;
1.942     foxr     3123:     }
1.324     www      3124: }
                   3125: 
                   3126: sub externalssi {
                   3127:     my ($url)=@_;
                   3128:     my $ua=new LWP::UserAgent;
                   3129:     my $request=new HTTP::Request('GET',$url);
                   3130:     my $response=$ua->request($request);
1.954     raeburn  3131:     if (wantarray) {
                   3132:         return ($response->content, $response);
                   3133:     } else {
                   3134:         return $response->content;
                   3135:     }
1.15      www      3136: }
1.254     www      3137: 
1.1172.2.98  raeburn  3138: # If the local copy of a replicated resource is outdated, trigger a
                   3139: # connection from the homeserver to flush the delayed queue. If no update
                   3140: # happens, remove local copies of outdated resource (and corresponding
                   3141: # metadata file).
                   3142: 
                   3143: sub remove_stale_resfile {
                   3144:     my ($url) = @_;
                   3145:     my $removed;
                   3146:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3147:         my $audom = $1;
                   3148:         my $auname = $2;
                   3149:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3150:             my $homeserver = &homeserver($auname,$audom);
                   3151:             unless (($homeserver eq 'no_host') ||
                   3152:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3153:                 my $fname = &filelocation('',$url);
                   3154:                 if (-e $fname) {
                   3155:                     my $ua=new LWP::UserAgent;
                   3156:                     $ua->timeout(5);
                   3157:                     my $protocol = $protocol{$homeserver};
                   3158:                     $protocol = 'http' if ($protocol ne 'https');
                   3159:                     my $hostname = &hostname($homeserver);
                   3160:                     if ($hostname) {
                   3161:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   3162:                         my $request=new HTTP::Request('HEAD',$uri);
                   3163:                         my $response=$ua->request($request);
                   3164:                         if ($response->is_success()) {
                   3165:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3166:                             my $locmodtime = (stat($fname))[9];
                   3167:                             if ($locmodtime < $remmodtime) {
                   3168:                                 my $stale;
                   3169:                                 my $answer = &reply('pong',$homeserver);
                   3170:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3171:                                     sleep(0.2);
                   3172:                                     $locmodtime = (stat($fname))[9];
                   3173:                                     if ($locmodtime < $remmodtime) {
                   3174:                                         my $posstransfer = $fname.'.in.transfer';
                   3175:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3176:                                             $removed = 1;
                   3177:                                         } else {
                   3178:                                             $stale = 1;
                   3179:                                         }
                   3180:                                     } else {
                   3181:                                         $removed = 1;
                   3182:                                     }
                   3183:                                 } else {
                   3184:                                     $stale = 1;
                   3185:                                 }
                   3186:                                 if ($stale) {
                   3187:                                     unlink($fname);
                   3188:                                     if ($uri!~/\.meta$/) {
                   3189:                                         unlink($fname.'.meta');
                   3190:                                     }
                   3191:                                     &reply("unsub:$fname",$homeserver);
                   3192:                                     $removed = 1;
                   3193:                                 }
                   3194:                             }
                   3195:                         }
                   3196:                     }
                   3197:                 }
                   3198:             }
                   3199:         }
                   3200:     }
                   3201:     return $removed;
                   3202: }
                   3203: 
1.492     albertel 3204: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3205: 
                   3206: sub allowuploaded {
                   3207:     my ($srcurl,$url)=@_;
                   3208:     $url=&clutter(&declutter($url));
                   3209:     my $dir=$url;
                   3210:     $dir=~s/\/[^\/]+$//;
                   3211:     my %httpref=();
                   3212:     my $httpurl=&hreflocation('',$url);
                   3213:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3214:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3215: }
1.477     raeburn  3216: 
1.1172.2.13  raeburn  3217: #
                   3218: # Determine if the current user should be able to edit a particular resource,
                   3219: # when viewing in course context.
                   3220: # (a) When viewing resource used to determine if "Edit" item is included in
                   3221: #     Functions.
                   3222: # (b) When displaying folder contents in course editor, used to determine if
                   3223: #     "Edit" link will be displayed alongside resource.
                   3224: #
                   3225: #  input: six args -- filename (decluttered), course number, course domain,
                   3226: #                   url, symb (if registered) and group (if this is a group
                   3227: #                   item -- e.g., bulletin board, group page etc.).
                   3228: #  output: array of five scalars --
                   3229: #          $cfile -- url for file editing if editable on current server
                   3230: #          $home -- homeserver of resource (i.e., for author if published,
                   3231: #                                           or course if uploaded.).
                   3232: #          $switchserver --  1 if server switch will be needed.
                   3233: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3234: #          $forceview -- 1 if icon/link should be to go to view mode
                   3235: #
                   3236: 
                   3237: sub can_edit_resource {
                   3238:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3239:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3240: #
                   3241: # For aboutme pages user can only edit his/her own.
                   3242: #
                   3243:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3244:         my ($sdom,$sname) = ($1,$2);
                   3245:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3246:             $home = $env{'user.home'};
                   3247:             $cfile = $resurl;
                   3248:             if ($env{'form.forceedit'}) {
                   3249:                 $forceview = 1;
                   3250:             } else {
                   3251:                 $forceedit = 1;
                   3252:             }
                   3253:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3254:         } else {
                   3255:             return;
                   3256:         }
                   3257:     }
                   3258: 
                   3259:     if ($env{'request.course.id'}) {
                   3260:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3261:         if ($group ne '') {
                   3262: # if this is a group homepage or group bulletin board, check group privs
                   3263:             my $allowed = 0;
                   3264:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3265:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3266:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3267:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3268:                     $allowed = 1;
                   3269:                 }
                   3270:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3271:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3272:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3273:                     $allowed = 1;
                   3274:                 }
                   3275:             }
                   3276:             if ($allowed) {
                   3277:                 $home=&homeserver($cnum,$cdom);
                   3278:                 if ($env{'form.forceedit'}) {
                   3279:                     $forceview = 1;
                   3280:                 } else {
                   3281:                     $forceedit = 1;
                   3282:                 }
                   3283:                 $cfile = $resurl;
                   3284:             } else {
                   3285:                 return;
                   3286:             }
                   3287:         } else {
1.1172.2.15  raeburn  3288:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3289:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3290:                     return;
                   3291:                 }
                   3292:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3293: #
                   3294: # No edit allowed where CC has switched to student role.
                   3295: #
                   3296:                 return;
                   3297:             }
                   3298:         }
                   3299:     }
                   3300: 
                   3301:     if ($file ne '') {
                   3302:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3303:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3304:                 $uploaded = 1;
                   3305:                 $incourse = 1;
                   3306:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3307:                     $cfile = &hreflocation('',$file);
                   3308:                     if ($env{'form.forceedit'}) {
                   3309:                         $forceview = 1;
                   3310:                     } else {
                   3311:                         $forceedit = 1;
                   3312:                     }
                   3313:                 }
                   3314:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3315:                 $incourse = 1;
                   3316:                 if ($env{'form.forceedit'}) {
                   3317:                     $forceview = 1;
                   3318:                 } else {
                   3319:                     $forceedit = 1;
                   3320:                 }
                   3321:                 $cfile = $resurl;
                   3322:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3323:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3324:                     $incourse = 1;
                   3325:                     if ($env{'form.forceedit'}) {
                   3326:                         $forceview = 1;
                   3327:                     } else {
                   3328:                         $forceedit = 1;
                   3329:                     }
                   3330:                     $cfile = $resurl;
                   3331:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3332:                     $incourse = 1;
                   3333:                     $cfile = $resurl.'/smpedit';
                   3334:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3335:                     $incourse = 1;
                   3336:                     if ($env{'form.forceedit'}) {
                   3337:                         $forceview = 1;
                   3338:                     } else {
                   3339:                         $forceedit = 1;
                   3340:                     }
                   3341:                     $cfile = $resurl;
1.1172.2.15  raeburn  3342:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3343:                     $incourse = 1;
                   3344:                     if ($env{'form.forceedit'}) {
                   3345:                         $forceview = 1;
                   3346:                     } else {
                   3347:                         $forceedit = 1;
                   3348:                     }
                   3349:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3350:                 }
                   3351:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3352:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3353:                 if (&is_on_map($template)) {
                   3354:                     $incourse = 1;
                   3355:                     $forceview = 1;
                   3356:                     $cfile = $template;
                   3357:                 }
                   3358:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3359:                     $incourse = 1;
                   3360:                     if ($env{'form.forceedit'}) {
                   3361:                         $forceview = 1;
                   3362:                     } else {
                   3363:                         $forceedit = 1;
                   3364:                     }
                   3365:                     $cfile = $resurl;
                   3366:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3367:                 $incourse = 1;
                   3368:                 $forceview = 1;
                   3369:                 if ($symb) {
                   3370:                     my ($map,$id,$res)=&decode_symb($symb);
                   3371:                     $env{'request.symb'} = $symb;
                   3372:                     $cfile = &clutter($res);
                   3373:                 } else {
                   3374:                     $cfile = $env{'form.suppurl'};
                   3375:                     $cfile =~ s{^http://}{};
                   3376:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3377:                 }
1.1172.2.31  raeburn  3378:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3379:                 if ($env{'form.forceedit'}) {
                   3380:                     $forceview = 1;
                   3381:                 } else {
                   3382:                     $forceedit = 1;
                   3383:                 }
                   3384:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3385:             }
                   3386:         }
                   3387:         if ($uploaded || $incourse) {
                   3388:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3389:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3390:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3391:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3392:             # Check that the user has permission to edit this resource
                   3393:             my $setpriv = 1;
                   3394:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3395:             if (defined($cfudom)) {
                   3396:                 $home=&homeserver($cfuname,$cfudom);
                   3397:                 $cfile=$file;
                   3398:             }
                   3399:         }
                   3400:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3401:             (($home ne '') && ($home ne 'no_host'))) {
                   3402:             my @ids=&current_machine_ids();
                   3403:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3404:                 $switchserver=1;
                   3405:             }
                   3406:         }
                   3407:     }
                   3408:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3409: }
                   3410: 
                   3411: sub is_course_upload {
                   3412:     my ($file,$cnum,$cdom) = @_;
                   3413:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3414:     $uploadpath =~ s{^\/}{};
                   3415:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3416:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3417:         return 1;
                   3418:     }
                   3419:     return;
                   3420: }
                   3421: 
                   3422: sub in_course {
                   3423:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3424:     if ($hideprivileged) {
                   3425:         my $skipuser;
1.1172.2.23  raeburn  3426:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3427:         my @possdoms = ($cdom);
                   3428:         if ($coursehash{'checkforpriv'}) {
                   3429:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3430:         }
                   3431:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3432:             $skipuser = 1;
                   3433:             if ($coursehash{'nothideprivileged'}) {
                   3434:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3435:                     my $user;
                   3436:                     if ($item =~ /:/) {
                   3437:                         $user = $item;
                   3438:                     } else {
                   3439:                         $user = join(':',split(/[\@]/,$item));
                   3440:                     }
                   3441:                     if ($user eq $uname.':'.$udom) {
                   3442:                         undef($skipuser);
                   3443:                         last;
                   3444:                     }
                   3445:                 }
                   3446:             }
                   3447:             if ($skipuser) {
                   3448:                 return 0;
                   3449:             }
                   3450:         }
                   3451:     }
                   3452:     $type ||= 'any';
                   3453:     if (!defined($cdom) || !defined($cnum)) {
                   3454:         my $cid  = $env{'request.course.id'};
                   3455:         $cdom = $env{'course.'.$cid.'.domain'};
                   3456:         $cnum = $env{'course.'.$cid.'.num'};
                   3457:     }
                   3458:     my $typesref;
                   3459:     if (($type eq 'any') || ($type eq 'all')) {
                   3460:         $typesref = ['active','previous','future'];
                   3461:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3462:         $typesref = [$type];
                   3463:     }
                   3464:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3465:                               $typesref,undef,[$cdom]);
                   3466:     my ($tmp) = keys(%roles);
                   3467:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3468:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3469:     if (@course_roles > 0) {
                   3470:         return 1;
                   3471:     }
                   3472:     return 0;
                   3473: }
                   3474: 
1.478     albertel 3475: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3476: # input: action, courseID, current domain, intended
1.637     raeburn  3477: #        path to file, source of file, instruction to parse file for objects,
                   3478: #        ref to hash for embedded objects,
                   3479: #        ref to hash for codebase of java objects.
1.1095    raeburn  3480: #        reference to scalar to accommodate mime type determined
                   3481: #          from File::MMagic if $parser = parse.
1.637     raeburn  3482: #
1.485     raeburn  3483: # output: url to file (if action was uploaddoc), 
                   3484: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3485: #
1.478     albertel 3486: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3487: # course.
1.477     raeburn  3488: #
1.478     albertel 3489: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3490: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3491: #          course's home server.
1.477     raeburn  3492: #
1.478     albertel 3493: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3494: #          be copied from $source (current location) to 
                   3495: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3496: #         and will then be copied to
                   3497: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3498: #         course's home server.
1.485     raeburn  3499: #
1.481     raeburn  3500: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3501: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3502: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3503: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3504: #         in course's home server.
1.637     raeburn  3505: #
1.477     raeburn  3506: 
                   3507: sub process_coursefile {
1.1095    raeburn  3508:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3509:         $mimetype)=@_;
1.477     raeburn  3510:     my $fetchresult;
1.638     albertel 3511:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3512:     if ($action eq 'propagate') {
1.638     albertel 3513:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3514: 			     $home);
1.481     raeburn  3515:     } else {
1.477     raeburn  3516:         my $fpath = '';
                   3517:         my $fname = $file;
1.478     albertel 3518:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3519:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3520:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3521:         if ($action eq 'copy') {
                   3522:             if ($source eq '') {
                   3523:                 $fetchresult = 'no source file';
                   3524:                 return $fetchresult;
                   3525:             } else {
                   3526:                 my $destination = $filepath.'/'.$fname;
                   3527:                 rename($source,$destination);
                   3528:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3529:                                  $home);
1.481     raeburn  3530:             }
                   3531:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3532:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3533:             print $fh $env{'form.'.$source};
1.481     raeburn  3534:             close($fh);
1.637     raeburn  3535:             if ($parser eq 'parse') {
1.1024    raeburn  3536:                 my $mm = new File::MMagic;
1.1095    raeburn  3537:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3538:                 if ($type eq 'text/html') {
1.1024    raeburn  3539:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3540:                     unless ($parse_result eq 'ok') {
                   3541:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3542:                     }
1.637     raeburn  3543:                 }
1.1095    raeburn  3544:                 if (ref($mimetype)) {
                   3545:                     $$mimetype = $type;
                   3546:                 } 
1.637     raeburn  3547:             }
1.477     raeburn  3548:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3549:                                  $home);
1.481     raeburn  3550:             if ($fetchresult eq 'ok') {
                   3551:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3552:             } else {
                   3553:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3554:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3555:                 return '/adm/notfound.html';
                   3556:             }
1.477     raeburn  3557:         }
                   3558:     }
1.485     raeburn  3559:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3560:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3561:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3562:     }
                   3563:     return $fetchresult;
                   3564: }
                   3565: 
1.637     raeburn  3566: sub build_filepath {
                   3567:     my ($fpath) = @_;
                   3568:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3569:     unless ($fpath eq '') {
                   3570:         my @parts=split('/',$fpath);
                   3571:         foreach my $part (@parts) {
                   3572:             $filepath.= '/'.$part;
                   3573:             if ((-e $filepath)!=1) {
                   3574:                 mkdir($filepath,0777);
                   3575:             }
                   3576:         }
                   3577:     }
                   3578:     return $filepath;
                   3579: }
                   3580: 
                   3581: sub store_edited_file {
1.638     albertel 3582:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3583:     my $file = $primary_url;
                   3584:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3585:     my $fpath = '';
                   3586:     my $fname = $file;
                   3587:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3588:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3589:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3590:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3591:     print $fh $content;
                   3592:     close($fh);
1.638     albertel 3593:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3594:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3595: 			  $home);
1.637     raeburn  3596:     if ($$fetchresult eq 'ok') {
                   3597:         return '/uploaded/'.$fpath.'/'.$fname;
                   3598:     } else {
1.638     albertel 3599:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3600: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3601:         return '/adm/notfound.html';
                   3602:     }
                   3603: }
                   3604: 
1.531     albertel 3605: sub clean_filename {
1.831     albertel 3606:     my ($fname,$args)=@_;
1.315     www      3607: # Replace Windows backslashes by forward slashes
1.257     www      3608:     $fname=~s/\\/\//g;
1.831     albertel 3609:     if (!$args->{'keep_path'}) {
                   3610:         # Get rid of everything but the actual filename
                   3611: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3612:     }
1.315     www      3613: # Replace spaces by underscores
                   3614:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3615: # Transliterate non-ascii text to ascii
                   3616:     my $lang = &Apache::lonlocal::current_language();
                   3617:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3618: # Replace all other weird characters by nothing
1.831     albertel 3619:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3620: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3621: # numbers
                   3622:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3623:     return $fname;
                   3624: }
1.1172.2.110  raeburn  3625: 
1.1051    raeburn  3626: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3627: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3628: # image with the same aspect ratio as the original, but with dimensions which do 
                   3629: # not exceed $resizewidth and $resizeheight.
                   3630:  
1.984     neumanie 3631: sub resizeImage {
1.1051    raeburn  3632:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3633:     my $ima = Image::Magick->new;
                   3634:     my $resized;
                   3635:     if (-e $img_path) {
                   3636:         $ima->Read($img_path);
                   3637:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3638:             my $width = $ima->Get('width');
                   3639:             my $height = $ima->Get('height');
                   3640:             if ($width > $resizewidth) {
                   3641: 	        my $factor = $width/$resizewidth;
                   3642:                 my $newheight = $height/$factor;
                   3643:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3644:                 $resized = 1;
                   3645:             }
                   3646:         }
                   3647:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3648:             my $width = $ima->Get('width');
                   3649:             my $height = $ima->Get('height');
                   3650:             if ($height > $resizeheight) {
                   3651:                 my $factor = $height/$resizeheight;
                   3652:                 my $newwidth = $width/$factor;
                   3653:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3654:                 $resized = 1;
                   3655:             }
                   3656:         }
                   3657:         if ($resized) {
                   3658:             $ima->Write($img_path);
                   3659:         }
                   3660:     }
                   3661:     return;
1.977     amueller 3662: }
                   3663: 
1.608     albertel 3664: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3665: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3666: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3667: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3668: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3669: #                   if 'coursedoc': upload to the current course
                   3670: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3671: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3672: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3673: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3674: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3675: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3676: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3677: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3678: #        $allfiles - reference to hash for embedded objects
                   3679: #        $codebase - reference to hash for codebase of java objects
                   3680: #        $desuname - username for permanent storage of uploaded file
                   3681: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3682: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3683: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3684: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3685: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3686: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3687: #                    from File::MMagic.
1.858     raeburn  3688: # 
1.686     albertel 3689: # output: url of file in userspace, or error: <message> 
                   3690: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3691: 
1.531     albertel 3692: sub userfileupload {
1.1090    raeburn  3693:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3694:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3695:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3696:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3697:     $fname=&clean_filename($fname);
1.1090    raeburn  3698:     # See if there is anything left
1.257     www      3699:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3700:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3701:     if ($fname =~ /^\./) {
                   3702:         my ($s,$usec) = &gettimeofday();
                   3703:         while (length($usec) < 6) {
                   3704:             $usec = '0'.$usec;
                   3705:         }
                   3706:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3707:     }
1.1090    raeburn  3708:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3709:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3710:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3711:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3712:         my $now = time;
1.1090    raeburn  3713:         my $filepath;
1.1095    raeburn  3714:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3715:              $filepath = 'tmp/helprequests/'.$now;
                   3716:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3717:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3718:                          '_'.$env{'user.domain'}.'/pending';
                   3719:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3720:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3721:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3722:                 $docudom = $destudom;
                   3723:             } else {
                   3724:                 $docudom = $env{'user.domain'};
                   3725:             }
1.1172.2.96  raeburn  3726:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3727:                 $docuname = $destuname;
                   3728:             } else {
                   3729:                 $docuname = $env{'user.name'};
                   3730:             }
                   3731:             if (exists($env{'form.group'})) {
                   3732:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3733:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3734:             }
                   3735:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3736:             if ($context eq 'canceloverwrite') {
                   3737:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3738:                 if (-e  $tempfile) {
                   3739:                     my @info = stat($tempfile);
                   3740:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3741:                         unlink($tempfile);
                   3742:                     }
                   3743:                 }
                   3744:                 return;
1.523     raeburn  3745:             }
                   3746:         }
1.1090    raeburn  3747:         # Create the directory if not present
1.741     raeburn  3748:         my @parts=split(/\//,$filepath);
                   3749:         my $fullpath = $perlvar{'lonDaemons'};
                   3750:         for (my $i=0;$i<@parts;$i++) {
                   3751:             $fullpath .= '/'.$parts[$i];
                   3752:             if ((-e $fullpath)!=1) {
                   3753:                 mkdir($fullpath,0777);
                   3754:             }
                   3755:         }
1.1172.2.96  raeburn  3756:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3757:         print $fh $env{'form.'.$formname};
                   3758:         close($fh);
1.1090    raeburn  3759:         if ($context eq 'existingfile') {
                   3760:             my @info = stat($fullpath.'/'.$fname);
                   3761:             return ($fullpath.'/'.$fname,$info[9]);
                   3762:         } else {
                   3763:             return $fullpath.'/'.$fname;
                   3764:         }
1.523     raeburn  3765:     }
1.995     raeburn  3766:     if ($subdir eq 'scantron') {
                   3767:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3768:     } else {
1.995     raeburn  3769:         $fname="$subdir/$fname";
                   3770:     }
1.1090    raeburn  3771:     if ($context eq 'coursedoc') {
1.638     albertel 3772: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3773: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3774:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3775:             return &finishuserfileupload($docuname,$docudom,
                   3776: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3777: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3778:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3779:         } else {
1.1172.2.21  raeburn  3780:             if ($env{'form.folder'}) {
                   3781:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3782:             }
1.638     albertel 3783:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3784: 				       $fname,$formname,$parser,
1.1095    raeburn  3785: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3786:         }
1.719     banghart 3787:     } elsif (defined($destuname)) {
                   3788:         my $docuname=$destuname;
                   3789:         my $docudom=$destudom;
1.860     raeburn  3790: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3791: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3792:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3793:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3794:     } else {
1.638     albertel 3795:         my $docuname=$env{'user.name'};
                   3796:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3797:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3798:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3799:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3800:         }
1.860     raeburn  3801: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3802: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3803:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3804:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3805:     }
1.271     www      3806: }
                   3807: 
                   3808: sub finishuserfileupload {
1.860     raeburn  3809:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3810:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3811:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3812:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3813:   
1.860     raeburn  3814:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3815:     $file=$fname;
                   3816:     if ($fname=~m|/|) {
                   3817:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3818: 	$path.=$fnamepath.'/';
                   3819:     }
1.259     www      3820:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3821:     my $count;
                   3822:     for ($count=4;$count<=$#parts;$count++) {
                   3823:         $filepath.="/$parts[$count]";
                   3824:         if ((-e $filepath)!=1) {
                   3825: 	    mkdir($filepath,0777);
                   3826:         }
                   3827:     }
1.984     neumanie 3828: 
1.258     www      3829: # Save the file
                   3830:     {
1.1172.2.96  raeburn  3831: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3832: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3833: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3834: 	    return '/adm/notfound.html';
                   3835: 	}
1.1090    raeburn  3836:         if ($context eq 'overwrite') {
1.1117    foxr     3837:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3838:             my $target = $filepath.'/'.$file;
                   3839:             if (-e $source) {
                   3840:                 my @info = stat($source);
                   3841:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3842:                     unless (&File::Copy::move($source,$target)) {
                   3843:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3844:                         return "Moving from $source failed";
                   3845:                     }
                   3846:                 } else {
                   3847:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3848:                 }
                   3849:             } else {
                   3850:                 return "Temporary file: $source missing";
                   3851:             }
                   3852:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3853: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3854: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3855: 	    return '/adm/notfound.html';
                   3856: 	}
1.570     albertel 3857: 	close(FH);
1.1051    raeburn  3858:         if ($resizewidth && $resizeheight) {
                   3859:             my $mm = new File::MMagic;
                   3860:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3861:             if ($mime_type =~ m{^image/}) {
                   3862: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3863:             }  
1.977     amueller 3864: 	}
1.258     www      3865:     }
1.1152    raeburn  3866:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3867:         if (ref($mimetype)) {
                   3868:             if ($$mimetype eq '') {
                   3869:                 my $mm = new File::MMagic;
                   3870:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3871:                 $$mimetype = $type;
                   3872:             }
                   3873:         }
                   3874:     }
1.1172.2.109  raeburn  3875:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3876:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3877:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3878:                                                        $allfiles,$codebase);
                   3879:             unless ($parse_result eq 'ok') {
                   3880:                 &logthis('Failed to parse '.$filepath.$file.
                   3881: 	   	         ' for embedded media: '.$parse_result); 
                   3882:             }
1.637     raeburn  3883:         }
1.1172.2.109  raeburn  3884:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3885:         my $format = $env{'form.scantron_format'};
                   3886:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3887:     }
1.860     raeburn  3888:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3889:         my $input = $filepath.'/'.$file;
                   3890:         my $output = $filepath.'/'.'tn-'.$file;
                   3891:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3892:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3893:         system({$args[0]} @args);
1.860     raeburn  3894:         if (-e $filepath.'/'.'tn-'.$file) {
                   3895:             $fetchthumb  = 1; 
                   3896:         }
                   3897:     }
1.858     raeburn  3898:  
1.259     www      3899: # Notify homeserver to grep it
                   3900: #
1.984     neumanie 3901:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3902:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3903:     if ($fetchresult eq 'ok') {
1.860     raeburn  3904:         if ($fetchthumb) {
                   3905:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3906:             if ($thumbresult ne 'ok') {
                   3907:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3908:                          $docuhome.': '.$thumbresult);
                   3909:             }
                   3910:         }
1.259     www      3911: #
1.258     www      3912: # Return the URL to it
1.494     albertel 3913:         return '/uploaded/'.$path.$file;
1.263     www      3914:     } else {
1.494     albertel 3915:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3916: 		 ': '.$fetchresult);
1.263     www      3917:         return '/adm/notfound.html';
1.858     raeburn  3918:     }
1.493     albertel 3919: }
                   3920: 
1.637     raeburn  3921: sub extract_embedded_items {
1.961     raeburn  3922:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3923:     my @state = ();
1.1164    raeburn  3924:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3925:     my %javafiles = (
                   3926:                       codebase => '',
                   3927:                       code => '',
                   3928:                       archive => ''
                   3929:                     );
                   3930:     my %mediafiles = (
                   3931:                       src => '',
                   3932:                       movie => '',
                   3933:                      );
1.648     raeburn  3934:     my $p;
                   3935:     if ($content) {
                   3936:         $p = HTML::LCParser->new($content);
                   3937:     } else {
1.961     raeburn  3938:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3939:     }
1.641     albertel 3940:     while (my $t=$p->get_token()) {
1.640     albertel 3941: 	if ($t->[0] eq 'S') {
                   3942: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3943: 	    push(@state, $tagname);
1.648     raeburn  3944:             if (lc($tagname) eq 'allow') {
                   3945:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3946:             }
1.640     albertel 3947: 	    if (lc($tagname) eq 'img') {
                   3948: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3949: 	    }
1.886     albertel 3950: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3951:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3952: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3953:                 }
1.886     albertel 3954: 	    }
1.645     raeburn  3955:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3956:                 my $src;
1.645     raeburn  3957:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3958:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3959:                 } else {
1.1164    raeburn  3960:                     if ($attr->{'src'} ne '') {
                   3961:                         $src = $attr->{'src'};
                   3962:                         &add_filetype($allfiles,$src,'src');
                   3963:                     }
                   3964:                 }
                   3965:                 my $text = $p->get_trimmed_text();
                   3966:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3967:                     my @swfargs = split(/,/,$1);
                   3968:                     foreach my $item (@swfargs) {
                   3969:                         $item =~ s/["']//g;
                   3970:                         $item =~ s/^\s+//;
                   3971:                         $item =~ s/\s+$//;
                   3972:                     }
                   3973:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3974:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3975:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3976:                         } else {
                   3977:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3978:                         }
                   3979:                     }
1.645     raeburn  3980:                 }
                   3981:             }
                   3982:             if (lc($tagname) eq 'link') {
                   3983:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3984:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3985:                 }
                   3986:             }
1.640     albertel 3987: 	    if (lc($tagname) eq 'object' ||
                   3988: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3989: 		foreach my $item (keys(%javafiles)) {
                   3990: 		    $javafiles{$item} = '';
                   3991: 		}
1.1164    raeburn  3992:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3993:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3994:                 }
1.640     albertel 3995: 	    }
                   3996: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3997: 		my $name = lc($attr->{'name'});
                   3998: 		foreach my $item (keys(%javafiles)) {
                   3999: 		    if ($name eq $item) {
                   4000: 			$javafiles{$item} = $attr->{'value'};
                   4001: 			last;
                   4002: 		    }
                   4003: 		}
1.1164    raeburn  4004:                 my $pathfrom;
1.640     albertel 4005: 		foreach my $item (keys(%mediafiles)) {
                   4006: 		    if ($name eq $item) {
1.1164    raeburn  4007:                         $pathfrom = $attr->{'value'};
                   4008:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4009: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4010: 			last;
                   4011: 		    }
                   4012: 		}
1.1164    raeburn  4013:                 if ($name eq 'flashvars') {
                   4014:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4015:                 }
                   4016:                 if ($pathfrom ne '') {
                   4017:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4018:                                          $pathfrom);
                   4019:                 }
1.640     albertel 4020: 	    }
                   4021: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4022: 		foreach my $item (keys(%javafiles)) {
                   4023: 		    if ($attr->{$item}) {
                   4024: 			$javafiles{$item} = $attr->{$item};
                   4025: 			last;
                   4026: 		    }
                   4027: 		}
                   4028: 		foreach my $item (keys(%mediafiles)) {
                   4029: 		    if ($attr->{$item}) {
                   4030: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4031: 			last;
                   4032: 		    }
                   4033: 		}
1.1164    raeburn  4034:                 if (lc($tagname) eq 'embed') {
                   4035:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4036:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4037:                                              $attr->{'src'});
                   4038:                     }
                   4039:                 }
1.640     albertel 4040: 	    }
1.1172.2.35  raeburn  4041:             if (lc($tagname) eq 'iframe') {
                   4042:                 my $src = $attr->{'src'} ;
                   4043:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4044:                     &add_filetype($allfiles,$src,'src');
                   4045:                 } elsif ($src =~ m{^/}) {
                   4046:                     if ($env{'request.course.id'}) {
                   4047:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4048:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4049:                         my $url = &hreflocation('',$fullpath);
                   4050:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4051:                             my $relpath = $1;
                   4052:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4053:                                 &add_filetype($allfiles,$1,'src');
                   4054:                             }
                   4055:                         }
                   4056:                     }
                   4057:                 }
                   4058:             }
1.1164    raeburn  4059:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4060:                 pop(@state);
1.1164    raeburn  4061:             }
1.640     albertel 4062: 	} elsif ($t->[0] eq 'E') {
                   4063: 	    my ($tagname) = ($t->[1]);
                   4064: 	    if ($javafiles{'codebase'} ne '') {
                   4065: 		$javafiles{'codebase'} .= '/';
                   4066: 	    }  
                   4067: 	    if (lc($tagname) eq 'applet' ||
                   4068: 		lc($tagname) eq 'object' ||
                   4069: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4070: 		) {
                   4071: 		foreach my $item (keys(%javafiles)) {
                   4072: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4073: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4074: 			&add_filetype($allfiles,$file,$item);
                   4075: 		    }
                   4076: 		}
                   4077: 	    } 
                   4078: 	    pop @state;
                   4079: 	}
                   4080:     }
1.1164    raeburn  4081:     foreach my $id (sort(keys(%flashvars))) {
                   4082:         if ($shockwave{$id} ne '') {
                   4083:             my @pairs = split(/\&/,$flashvars{$id});
                   4084:             foreach my $pair (@pairs) {
                   4085:                 my ($key,$value) = split(/\=/,$pair);
                   4086:                 if ($key eq 'thumb') {
                   4087:                     &add_filetype($allfiles,$value,$key);
                   4088:                 } elsif ($key eq 'content') {
                   4089:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4090:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4091:                     if ($ext ne '') {
                   4092:                         &add_filetype($allfiles,$path.$value,$ext);
                   4093:                     }
                   4094:                 }
                   4095:             }
                   4096:         }
                   4097:     }
1.637     raeburn  4098:     return 'ok';
                   4099: }
                   4100: 
1.639     albertel 4101: sub add_filetype {
                   4102:     my ($allfiles,$file,$type)=@_;
                   4103:     if (exists($allfiles->{$file})) {
                   4104: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4105: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4106: 	}
                   4107:     } else {
                   4108: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4109:     }
                   4110: }
                   4111: 
1.1164    raeburn  4112: sub embedded_dependency {
                   4113:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4114:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4115:         if (($identifier ne '') &&
                   4116:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4117:             ($pathfrom ne '')) {
                   4118:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4119:             foreach my $dep (@{$related->{$identifier}}) {
                   4120:                 &add_filetype($allfiles,$path.$dep,'object');
                   4121:             }
                   4122:         }
                   4123:     }
                   4124:     return;
                   4125: }
                   4126: 
1.1172.2.109  raeburn  4127: sub bubblesheet_converter {
                   4128:     my ($cdom,$fullpath,$config,$format) = @_;
                   4129:     if ((&domain($cdom) ne '') &&
                   4130:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4131:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4132:         my (%csvcols,%csvoptions);
                   4133:         if (ref($config->{'fields'}) eq 'HASH') {
                   4134:             %csvcols = %{$config->{'fields'}};
                   4135:         }
                   4136:         if (ref($config->{'options'}) eq 'HASH') {
                   4137:             %csvoptions = %{$config->{'options'}};
                   4138:         }
                   4139:         my %csvbynum = reverse(%csvcols);
                   4140:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4141:         if (keys(%scantronconf)) {
                   4142:             my %bynum = (
                   4143:                           $scantronconf{CODEstart} => 'CODEstart',
                   4144:                           $scantronconf{IDstart}   => 'IDstart',
                   4145:                           $scantronconf{PaperID}   => 'PaperID',
                   4146:                           $scantronconf{FirstName} => 'FirstName',
                   4147:                           $scantronconf{LastName}  => 'LastName',
                   4148:                           $scantronconf{Qstart}    => 'Qstart',
                   4149:                         );
                   4150:             my @ordered;
                   4151:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4152:                 push(@ordered,$bynum{$item});
                   4153:             }
                   4154:             my %mapstart = (
                   4155:                               CODEstart => 'CODE',
                   4156:                               IDstart   => 'ID',
                   4157:                               PaperID   => 'PaperID',
                   4158:                               FirstName => 'FirstName',
                   4159:                               LastName  => 'LastName',
                   4160:                               Qstart    => 'FirstQuestion',
                   4161:                            );
                   4162:             my %maplength = (
                   4163:                               CODEstart => 'CODElength',
                   4164:                               IDstart   => 'IDlength',
                   4165:                               PaperID   => 'PaperIDlength',
                   4166:                               FirstName => 'FirstNamelength',
                   4167:                               LastName  => 'LastNamelength',
                   4168:             );
                   4169:             if (open(my $fh,'<',$fullpath)) {
                   4170:                 my $output;
                   4171:                 my %lettdig = &letter_to_digits();
                   4172:                 my %diglett = reverse(%lettdig);
                   4173:                 my $numletts = scalar(keys(%lettdig));
                   4174:                 my $num = 0;
                   4175:                 while (my $line=<$fh>) {
                   4176:                     $num ++;
                   4177:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4178:                     $line =~ s{[\r\n]+$}{};
                   4179:                     my %found;
                   4180:                     my @values = split(/,/,$line);
                   4181:                     my ($qstart,$record);
                   4182:                     for (my $i=0; $i<@values; $i++) {
                   4183:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4184:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4185:                             if ($values[$i] eq '') {
                   4186:                                 $values[$i] = $scantronconf{'Qoff'};
                   4187:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4188:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4189:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4190:                                 }
                   4191:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4192:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4193:                                     $values[$i] = $diglett{$values[$i]};
                   4194:                                 }
                   4195:                             } else {
                   4196:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4197:                                     my $digit;
                   4198:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4199:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4200:                                         if ($values[$i] eq 'J') {
                   4201:                                             $digit += $numletts;
                   4202:                                         }
                   4203:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4204:                                         $digit = $values[$i]-1;
                   4205:                                         if ($values[$i] eq '0') {
                   4206:                                             $digit += $numletts;
                   4207:                                         }
                   4208:                                     }
                   4209:                                     my $qval='';
                   4210:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4211:                                         if ($j == $digit) {
                   4212:                                             $qval .= $scantronconf{'Qon'};
                   4213:                                         } else {
                   4214:                                             $qval .= $scantronconf{'Qoff'};
                   4215:                                         }
                   4216:                                     }
                   4217:                                     $values[$i] = $qval;
                   4218:                                 }
                   4219:                             }
                   4220:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4221:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4222:                             }
                   4223:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4224:                             if ($numblank > 0) {
                   4225:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4226:                             }
                   4227:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4228:                                 $qstart = $i;
                   4229:                                 $found{$csvbynum{$i}} = $values[$i];
                   4230:                             } else {
                   4231:                                 $found{'FirstQuestion'} .= $values[$i];
                   4232:                             }
                   4233:                         } elsif (exists($csvbynum{$i})) {
                   4234:                             if ($csvoptions{'rem'}) {
                   4235:                                 $values[$i] =~ s/^\s+//;
                   4236:                             }
                   4237:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4238:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4239:                                     $values[$i] = '0'.$values[$i];
                   4240:                                 }
                   4241:                             }
                   4242:                             $found{$csvbynum{$i}} = $values[$i];
                   4243:                         }
                   4244:                     }
                   4245:                     foreach my $item (@ordered) {
                   4246:                         my $currlength = 1+length($record);
                   4247:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4248:                         if ($numspaces > 0) {
                   4249:                             $record .= (' ' x $numspaces);
                   4250:                         }
                   4251:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4252:                             unless ($item eq 'Qstart') {
                   4253:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4254:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4255:                                 }
                   4256:                             }
                   4257:                             $record .= $found{$mapstart{$item}};
                   4258:                         }
                   4259:                     }
                   4260:                     $output .= "$record\n";
                   4261:                 }
                   4262:                 close($fh);
                   4263:                 if ($output) {
                   4264:                     if (open(my $fh,'>',$fullpath)) {
                   4265:                         print $fh $output;
                   4266:                         close($fh);
                   4267:                     }
                   4268:                 }
                   4269:             }
                   4270:         }
                   4271:         return;
                   4272:     }
                   4273: }
                   4274: 
                   4275: sub letter_to_digits {
                   4276:     my %lettdig = (
                   4277:                     A => 1,
                   4278:                     B => 2,
                   4279:                     C => 3,
                   4280:                     D => 4,
                   4281:                     E => 5,
                   4282:                     F => 6,
                   4283:                     G => 7,
                   4284:                     H => 8,
                   4285:                     I => 9,
                   4286:                     J => 0,
                   4287:                   );
                   4288:     return %lettdig;
                   4289: }
                   4290: 
                   4291: sub get_scantron_config {
                   4292:     my ($which,$cdom) = @_;
                   4293:     my @lines = &get_scantronformat_file($cdom);
                   4294:     my %config;
                   4295:     #FIXME probably should move to XML it has already gotten a bit much now
                   4296:     foreach my $line (@lines) {
                   4297:         my ($name,$descrip)=split(/:/,$line);
                   4298:         if ($name ne $which ) { next; }
                   4299:         chomp($line);
                   4300:         my @config=split(/:/,$line);
                   4301:         $config{'name'}=$config[0];
                   4302:         $config{'description'}=$config[1];
                   4303:         $config{'CODElocation'}=$config[2];
                   4304:         $config{'CODEstart'}=$config[3];
                   4305:         $config{'CODElength'}=$config[4];
                   4306:         $config{'IDstart'}=$config[5];
                   4307:         $config{'IDlength'}=$config[6];
                   4308:         $config{'Qstart'}=$config[7];
                   4309:         $config{'Qlength'}=$config[8];
                   4310:         $config{'Qoff'}=$config[9];
                   4311:         $config{'Qon'}=$config[10];
                   4312:         $config{'PaperID'}=$config[11];
                   4313:         $config{'PaperIDlength'}=$config[12];
                   4314:         $config{'FirstName'}=$config[13];
                   4315:         $config{'FirstNamelength'}=$config[14];
                   4316:         $config{'LastName'}=$config[15];
                   4317:         $config{'LastNamelength'}=$config[16];
                   4318:         $config{'BubblesPerRow'}=$config[17];
                   4319:         last;
                   4320:     }
                   4321:     return %config;
                   4322: }
                   4323: 
                   4324: sub get_scantronformat_file {
                   4325:     my ($cdom) = @_;
                   4326:     if ($cdom eq '') {
                   4327:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4328:     }
                   4329:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4330:     my $gottab = 0;
                   4331:     my @lines;
                   4332:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4333:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4334:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4335:             if ($formatfile ne '-1') {
                   4336:                 @lines = split("\n",$formatfile,-1);
                   4337:                 $gottab = 1;
                   4338:             }
                   4339:         }
                   4340:     }
                   4341:     if (!$gottab) {
                   4342:         my $confname = $cdom.'-domainconfig';
                   4343:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4344:         my $formatfile = &getfile($default);
                   4345:         if ($formatfile ne '-1') {
                   4346:             @lines = split("\n",$formatfile,-1);
                   4347:             $gottab = 1;
                   4348:         }
                   4349:     }
                   4350:     if (!$gottab) {
                   4351:         my @domains = &current_machine_domains();
                   4352:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4353:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4354:                 @lines = <$fh>;
                   4355:                 close($fh);
                   4356:             }
                   4357:         } else {
                   4358:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4359:                 @lines = <$fh>;
                   4360:                 close($fh);
                   4361:             }
                   4362:         }
                   4363:     }
                   4364:     return @lines;
                   4365: }
                   4366: 
1.493     albertel 4367: sub removeuploadedurl {
1.984     neumanie 4368:     my ($url)=@_;	
                   4369:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4370:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4371: }
                   4372: 
                   4373: sub removeuserfile {
                   4374:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4375:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4376:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4377:     if ($result eq 'ok') {	
1.798     raeburn  4378:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4379:             my $metafile = $fname.'.meta';
                   4380:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4381: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4382:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4383:             my $sqlresult = 
1.823     albertel 4384:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4385:                                         'portfolio_metadata',$group,
                   4386:                                         'delete');
1.798     raeburn  4387:         }
                   4388:     }
                   4389:     return $result;
1.257     www      4390: }
1.15      www      4391: 
1.530     albertel 4392: sub mkdiruserfile {
                   4393:     my ($docuname,$docudom,$dir)=@_;
                   4394:     my $home=&homeserver($docuname,$docudom);
                   4395:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4396: }
                   4397: 
1.531     albertel 4398: sub renameuserfile {
                   4399:     my ($docuname,$docudom,$old,$new)=@_;
                   4400:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4401:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4402:                         &escape("$old").':'.&escape("$new"),$home);
                   4403:     if ($result eq 'ok') {
                   4404:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4405:             my $oldmeta = $old.'.meta';
                   4406:             my $newmeta = $new.'.meta';
                   4407:             my $metaresult = 
                   4408:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4409: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4410:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4411:             my $sqlresult = 
1.823     albertel 4412:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4413:                                         'portfolio_metadata',$group,
                   4414:                                         'delete');
1.798     raeburn  4415:         }
                   4416:     }
                   4417:     return $result;
1.531     albertel 4418: }
                   4419: 
1.14      www      4420: # ------------------------------------------------------------------------- Log
                   4421: 
                   4422: sub log {
                   4423:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4424:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4425: }
                   4426: 
                   4427: # ------------------------------------------------------------------ Course Log
1.352     www      4428: #
                   4429: # This routine flushes several buffers of non-mission-critical nature
                   4430: #
1.157     www      4431: 
                   4432: sub flushcourselogs {
1.352     www      4433:     &logthis('Flushing log buffers');
                   4434: #
                   4435: # course logs
                   4436: # This is a log of all transactions in a course, which can be used
                   4437: # for data mining purposes
                   4438: #
                   4439: # It also collects the courseid database, which lists last transaction
                   4440: # times and course titles for all courseids
                   4441: #
                   4442:     my %courseidbuffer=();
1.921     raeburn  4443:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4444:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4445: 		          &escape($courselogs{$crsid}),
                   4446: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4447: 	    delete $courselogs{$crsid};
                   4448:         } else {
                   4449:             &logthis('Failed to flush log buffer for '.$crsid);
                   4450:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4451:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4452:                         " exceeded maximum size, deleting.</font>");
                   4453:                delete $courselogs{$crsid};
                   4454:             }
1.352     www      4455:         }
1.920     raeburn  4456:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4457:             'description' => $coursedescrbuf{$crsid},
                   4458:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4459:             'type'        => $coursetypebuf{$crsid},
                   4460:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4461:         };
1.191     harris41 4462:     }
1.352     www      4463: #
                   4464: # Write course id database (reverse lookup) to homeserver of courses 
                   4465: # Is used in pickcourse
                   4466: #
1.840     albertel 4467:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4468:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4469:                                     $courseidbuffer{$crs_home},
                   4470:                                     $crs_home,'timeonly');
1.352     www      4471:     }
                   4472: #
                   4473: # File accesses
                   4474: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4475: #
1.449     matthew  4476:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4477:         if ($entry =~ /___count$/) {
                   4478:             my ($dom,$name);
1.807     albertel 4479:             ($dom,$name,undef)=
1.811     albertel 4480: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4481:             if (! defined($dom) || $dom eq '' || 
                   4482:                 ! defined($name) || $name eq '') {
1.620     albertel 4483:                 my $cid = $env{'request.course.id'};
                   4484:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4485:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4486:             }
1.450     matthew  4487:             my $value = $accesshash{$entry};
                   4488:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4489:             my %temphash=($url => $value);
1.449     matthew  4490:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4491:             if ($result eq 'ok') {
                   4492:                 delete $accesshash{$entry};
                   4493:             }
                   4494:         } else {
1.811     albertel 4495:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4496:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4497:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4498:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4499:                 delete $accesshash{$entry};
                   4500:             }
1.185     www      4501:         }
1.191     harris41 4502:     }
1.352     www      4503: #
                   4504: # Roles
                   4505: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4506: #
1.800     albertel 4507:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4508:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4509: 	    split(/\:/,$entry);
                   4510:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4511:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4512:                 $rudom,$runame) eq 'ok') {
                   4513: 	    delete $userrolehash{$entry};
                   4514:         }
                   4515:     }
1.662     raeburn  4516: #
1.1172.2.90  raeburn  4517: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4518: #
                   4519:     my %domrolebuffer = ();
1.1000    raeburn  4520:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4521:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4522:         if ($domrolebuffer{$rudom}) {
                   4523:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4524:                       '='.&escape($domainrolehash{$entry});
                   4525:         } else {
                   4526:             $domrolebuffer{$rudom}.=&escape($entry).
                   4527:                       '='.&escape($domainrolehash{$entry});
                   4528:         }
                   4529:         delete $domainrolehash{$entry};
                   4530:     }
                   4531:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4532:         my %servers;
                   4533:         if (defined(&domain($dom,'primary'))) {
                   4534:             my $primary=&domain($dom,'primary');
                   4535:             my $hostname=&hostname($primary);
                   4536:             $servers{$primary} = $hostname;
                   4537:         } else {
                   4538:             %servers = &get_servers($dom,'library');
                   4539:         }
1.841     albertel 4540: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4541: 	    if (&reply('domroleput:'.$dom.':'.
                   4542: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4543: 	        last;
                   4544: 	    } else {
1.841     albertel 4545: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4546: 	    }
1.662     raeburn  4547:         }
                   4548:     }
1.186     www      4549:     $dumpcount++;
1.157     www      4550: }
                   4551: 
                   4552: sub courselog {
                   4553:     my $what=shift;
1.158     www      4554:     $what=time.':'.$what;
1.620     albertel 4555:     unless ($env{'request.course.id'}) { return ''; }
                   4556:     $coursedombuf{$env{'request.course.id'}}=
                   4557:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4558:     $coursenumbuf{$env{'request.course.id'}}=
                   4559:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4560:     $coursehombuf{$env{'request.course.id'}}=
                   4561:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4562:     $coursedescrbuf{$env{'request.course.id'}}=
                   4563:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4564:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4565:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4566:     $courseownerbuf{$env{'request.course.id'}}=
                   4567:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4568:     $coursetypebuf{$env{'request.course.id'}}=
                   4569:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4570:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4571: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4572:     } else {
1.620     albertel 4573: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4574:     }
1.620     albertel 4575:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4576: 	&flushcourselogs();
                   4577:     }
1.158     www      4578: }
                   4579: 
                   4580: sub courseacclog {
                   4581:     my $fnsymb=shift;
1.620     albertel 4582:     unless ($env{'request.course.id'}) { return ''; }
                   4583:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4584:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4585:         $what.=':POST';
1.583     matthew  4586:         # FIXME: Probably ought to escape things....
1.800     albertel 4587: 	foreach my $key (keys(%env)) {
                   4588:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4589:                 my $formitem = $1;
                   4590:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4591:                     $what.=':'.$formitem.'='.$env{$key};
                   4592:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4593:                     $what.=':'.$formitem.'='.$env{$key};
                   4594:                 }
1.158     www      4595:             }
1.191     harris41 4596:         }
1.583     matthew  4597:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4598:         # FIXME: We should not be depending on a form parameter that someone
                   4599:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4600:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4601:             $what.= ':POST';
                   4602:             # FIXME: Probably ought to escape things....
                   4603:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4604:                                  'crsdiscuss') {
1.620     albertel 4605:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4606:             }
                   4607:         }
1.158     www      4608:     }
                   4609:     &courselog($what);
1.149     www      4610: }
                   4611: 
1.185     www      4612: sub countacc {
                   4613:     my $url=&declutter(shift);
1.458     matthew  4614:     return if (! defined($url) || $url eq '');
1.620     albertel 4615:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4616: #
                   4617: # Mark that this url was used in this course
                   4618: #
1.620     albertel 4619:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4620: #
                   4621: # Increase the access count for this resource in this child process
                   4622: #
1.281     www      4623:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4624:     $accesshash{$key}++;
1.185     www      4625: }
1.349     www      4626: 
1.361     www      4627: sub linklog {
                   4628:     my ($from,$to)=@_;
                   4629:     $from=&declutter($from);
                   4630:     $to=&declutter($to);
                   4631:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4632:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4633: }
1.1160    www      4634: 
                   4635: sub statslog {
                   4636:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4637:     if ($users<2) { return; }
                   4638:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4639:             'course'       => $env{'request.course.id'},
                   4640:             'sections'     => '"all"',
                   4641:             'num_students' => $users,
                   4642:             'part'         => $part,
                   4643:             'symb'         => $symb,
                   4644:             'mean_tries'   => $av_attempts,
                   4645:             'deg_of_diff'  => $degdiff});
                   4646:     foreach my $key (keys(%dynstore)) {
                   4647:         $accesshash{$key}=$dynstore{$key};
                   4648:     }
                   4649: }
1.361     www      4650:   
1.349     www      4651: sub userrolelog {
                   4652:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4653:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4654:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4655:        $userrolehash
                   4656:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4657:                     =$tend.':'.$tstart;
1.662     raeburn  4658:     }
1.1169    droeschl 4659:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4660:        $userrolehash
                   4661:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4662:                     =$tend.':'.$tstart;
                   4663:     }
1.1172.2.90  raeburn  4664:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4665:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4666:        $domainrolehash
                   4667:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4668:                     = $tend.':'.$tstart;
                   4669:     }
1.351     www      4670: }
                   4671: 
1.957     raeburn  4672: sub courserolelog {
                   4673:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4674:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4675:         my $cdom = $1;
                   4676:         my $cnum = $2;
                   4677:         my $sec = $3;
                   4678:         my $namespace = 'rolelog';
                   4679:         my %storehash = (
                   4680:                            role    => $trole,
                   4681:                            start   => $tstart,
                   4682:                            end     => $tend,
                   4683:                            selfenroll => $selfenroll,
                   4684:                            context    => $context,
                   4685:                         );
                   4686:         if ($trole eq 'gr') {
                   4687:             $namespace = 'groupslog';
                   4688:             $storehash{'group'} = $sec;
                   4689:         } else {
                   4690:             $storehash{'section'} = $sec;
                   4691:         }
                   4692:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4693:                    $domain,$cnum,$cdom);
                   4694:         if (($trole ne 'st') || ($sec ne '')) {
                   4695:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4696:         }
                   4697:     }
                   4698:     return;
                   4699: }
                   4700: 
1.1172.2.9  raeburn  4701: sub domainrolelog {
                   4702:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4703:     if ($area =~ m{^/($match_domain)/$}) {
                   4704:         my $cdom = $1;
                   4705:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4706:         my $namespace = 'rolelog';
                   4707:         my %storehash = (
                   4708:                            role    => $trole,
                   4709:                            start   => $tstart,
                   4710:                            end     => $tend,
                   4711:                            context => $context,
                   4712:                         );
                   4713:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4714:                    $domain,$domconfiguser,$cdom);
                   4715:     }
                   4716:     return;
                   4717: 
                   4718: }
                   4719: 
                   4720: sub coauthorrolelog {
                   4721:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4722:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4723:         my $audom = $1;
                   4724:         my $auname = $2;
                   4725:         my $namespace = 'rolelog';
                   4726:         my %storehash = (
                   4727:                            role    => $trole,
                   4728:                            start   => $tstart,
                   4729:                            end     => $tend,
                   4730:                            context => $context,
                   4731:                         );
                   4732:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4733:                    $domain,$auname,$audom);
                   4734:     }
                   4735:     return;
                   4736: }
                   4737: 
1.351     www      4738: sub get_course_adv_roles {
1.948     raeburn  4739:     my ($cid,$codes) = @_;
1.620     albertel 4740:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4741:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4742:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4743:     my %nothide=();
1.800     albertel 4744:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4745:         if ($user !~ /:/) {
                   4746: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4747:         } else {
                   4748:             $nothide{$user}=1;
                   4749:         }
1.470     www      4750:     }
1.1172.2.23  raeburn  4751:     my @possdoms = ($coursehash{'domain'});
                   4752:     if ($coursehash{'checkforpriv'}) {
                   4753:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4754:     }
1.351     www      4755:     my %returnhash=();
                   4756:     my %dumphash=
                   4757:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4758:     my $now=time;
1.997     raeburn  4759:     my %privileged;
1.1000    raeburn  4760:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4761: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4762:         if (($tstart) && ($tstart<0)) { next; }
                   4763:         if (($tend) && ($tend<$now)) { next; }
                   4764:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4765:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4766: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4767:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4768:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4769: 	if ($role eq 'cr') { next; }
1.948     raeburn  4770:         if ($codes) {
                   4771:             if ($section) { $role .= ':'.$section; }
                   4772:             if ($returnhash{$role}) {
                   4773:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4774:             } else {
                   4775:                 $returnhash{$role}=$username.':'.$domain;
                   4776:             }
1.351     www      4777:         } else {
1.988     raeburn  4778:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4779:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4780:             if ($returnhash{$key}) {
                   4781: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4782:             } else {
                   4783:                 $returnhash{$key}=$username.':'.$domain;
                   4784:             }
1.351     www      4785:         }
1.948     raeburn  4786:     }
1.400     www      4787:     return %returnhash;
                   4788: }
                   4789: 
                   4790: sub get_my_roles {
1.937     raeburn  4791:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4792:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4793:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4794:     my (%dumphash,%nothide);
1.1086    raeburn  4795:     if ($context eq 'userroles') {
1.1166    raeburn  4796:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4797:     } else {
1.1172.2.23  raeburn  4798:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4799:         if ($hidepriv) {
                   4800:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4801:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4802:                 if ($user !~ /:/) {
                   4803:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4804:                 } else {
                   4805:                     $nothide{$user} = 1;
                   4806:                 }
                   4807:             }
                   4808:         }
1.858     raeburn  4809:     }
1.400     www      4810:     my %returnhash=();
                   4811:     my $now=time;
1.999     raeburn  4812:     my %privileged;
1.800     albertel 4813:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4814:         my ($role,$tend,$tstart);
                   4815:         if ($context eq 'userroles') {
1.1149    raeburn  4816:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4817: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4818:         } else {
                   4819:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4820:         }
1.400     www      4821:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4822:         my $status = 'active';
1.939     raeburn  4823:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4824:             $status = 'previous';
                   4825:         } 
                   4826:         if (($tstart) && ($now<$tstart)) {
                   4827:             $status = 'future';
                   4828:         }
                   4829:         if (ref($types) eq 'ARRAY') {
                   4830:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4831:                 next;
                   4832:             } 
                   4833:         } else {
                   4834:             if ($status ne 'active') {
                   4835:                 next;
                   4836:             }
                   4837:         }
1.867     raeburn  4838:         my ($rolecode,$username,$domain,$section,$area);
                   4839:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4840:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4841:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4842:         } else {
                   4843:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4844:         }
1.832     raeburn  4845:         if (ref($roledoms) eq 'ARRAY') {
                   4846:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4847:                 next;
                   4848:             }
                   4849:         }
                   4850:         if (ref($roles) eq 'ARRAY') {
                   4851:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4852:                 if ($role =~ /^cr\//) {
                   4853:                     if (!grep(/^cr$/,@{$roles})) {
                   4854:                         next;
                   4855:                     }
1.1104    raeburn  4856:                 } elsif ($role =~ /^gr\//) {
                   4857:                     if (!grep(/^gr$/,@{$roles})) {
                   4858:                         next;
                   4859:                     }
1.922     raeburn  4860:                 } else {
                   4861:                     next;
                   4862:                 }
1.832     raeburn  4863:             }
1.867     raeburn  4864:         }
1.937     raeburn  4865:         if ($hidepriv) {
1.1172.2.23  raeburn  4866:             my @privroles = ('dc','su');
1.999     raeburn  4867:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4868:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4869:             } else {
1.1172.2.23  raeburn  4870:                 my $possdoms = [$domain];
                   4871:                 if (ref($roledoms) eq 'ARRAY') {
                   4872:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4873:                 }
1.1172.2.23  raeburn  4874:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4875:                     if (!$nothide{$username.':'.$domain}) {
                   4876:                         next;
                   4877:                     }
                   4878:                 }
1.937     raeburn  4879:             }
                   4880:         }
1.933     raeburn  4881:         if ($withsec) {
                   4882:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4883:                 $tstart.':'.$tend;
                   4884:         } else {
                   4885:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4886:         }
1.832     raeburn  4887:     }
1.373     www      4888:     return %returnhash;
1.399     www      4889: }
                   4890: 
1.1172.2.89  raeburn  4891: sub get_all_adhocroles {
                   4892:     my ($dom) = @_;
                   4893:     my @roles_by_num = ();
                   4894:     my %domdefaults = &get_domain_defaults($dom);
                   4895:     my (%description,%access_in_dom,%access_info);
                   4896:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4897:         my $count = 0;
                   4898:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4899:         my %ordered;
                   4900:         foreach my $role (sort(keys(%domcurrent))) {
                   4901:             my ($order,$desc,$access_in_dom);
                   4902:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4903:                 $order = $domcurrent{$role}{'order'};
                   4904:                 $desc = $domcurrent{$role}{'desc'};
                   4905:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4906:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4907:             }
                   4908:             if ($order eq '') {
                   4909:                 $order = $count;
                   4910:             }
                   4911:             $ordered{$order} = $role;
                   4912:             if ($desc ne '') {
                   4913:                 $description{$role} = $desc;
                   4914:             } else {
                   4915:                 $description{$role}= $role;
                   4916:             }
                   4917:             $count++;
                   4918:         }
                   4919:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4920:             push(@roles_by_num,$ordered{$item});
                   4921:         }
                   4922:     }
                   4923:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4924: }
                   4925: 
                   4926: sub get_my_adhocroles {
                   4927:     my ($cid,$checkreg) = @_;
                   4928:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4929:     if ($env{'request.course.id'} eq $cid) {
                   4930:         $cdom = $env{'course.'.$cid.'.domain'};
                   4931:         $cnum = $env{'course.'.$cid.'.num'};
                   4932:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4933:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4934:         $cdom = $1;
                   4935:         $cnum = $2;
                   4936:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4937:                                      $cdom,$cnum);
                   4938:     }
                   4939:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4940:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4941:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4942:         if ($rosterhash{$user} ne '') {
                   4943:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4944:             return ([],{}) if ($type eq 'auto');
                   4945:         }
                   4946:     }
                   4947:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4948:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4949:             my $then=$env{'user.login.time'};
                   4950:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4951:             if (!$update) {
                   4952:                 $update = $then;
                   4953:             }
                   4954:             my @liveroles;
                   4955:             foreach my $role ('dh','da') {
                   4956:                 if ($env{"user.role.$role./$cdom/"}) {
                   4957:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4958:                     my $limit = $update;
                   4959:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4960:                         $limit = $then;
                   4961:                     }
                   4962:                     my $activerole = 1;
                   4963:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4964:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4965:                     if ($activerole) {
                   4966:                         push(@liveroles,$role);
                   4967:                     }
                   4968:                 }
                   4969:             }
                   4970:             if (@liveroles) {
1.1172.2.89  raeburn  4971:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4972:                     my ($accessref,$accessinfo,%access_in_dom);
                   4973:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4974:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4975:                         if (@{$roles_by_num}) {
                   4976:                             my %settings;
                   4977:                             if ($env{'request.course.id'} eq $cid) {
                   4978:                                 foreach my $envkey (keys(%env)) {
                   4979:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4980:                                         $settings{$1} = $env{$envkey};
                   4981:                                     }
                   4982:                                 }
                   4983:                             } else {
                   4984:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4985:                             }
                   4986:                             my %setincrs;
                   4987:                             if ($settings{'internal.adhocaccess'}) {
                   4988:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4989:                             }
                   4990:                             my @statuses;
                   4991:                             if ($env{'environment.inststatus'}) {
                   4992:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4993:                             }
                   4994:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4995:                             if (ref($accessref) eq 'HASH') {
                   4996:                                 %access_in_dom = %{$accessref};
                   4997:                             }
                   4998:                             foreach my $role (@{$roles_by_num}) {
                   4999:                                 my ($curraccess,@okstatus,@personnel);
                   5000:                                 if ($setincrs{$role}) {
                   5001:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5002:                                     if ($curraccess eq 'status') {
                   5003:                                         @okstatus = split(/\&/,$rest);
                   5004:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5005:                                         @personnel = split(/\&/,$rest);
                   5006:                                     }
                   5007:                                 } else {
                   5008:                                     $curraccess = $access_in_dom{$role};
                   5009:                                     if (ref($accessinfo) eq 'HASH') {
                   5010:                                         if ($curraccess eq 'status') {
                   5011:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5012:                                                 @okstatus = @{$accessinfo->{$role}};
                   5013:                                             }
                   5014:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5015:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5016:                                                 @personnel = @{$accessinfo->{$role}};
                   5017:                                             }
                   5018:                                         }
                   5019:                                     }
                   5020:                                 }
                   5021:                                 if ($curraccess eq 'none') {
                   5022:                                     next;
                   5023:                                 } elsif ($curraccess eq 'all') {
                   5024:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5025:                                 } elsif ($curraccess eq 'dh') {
                   5026:                                     if (grep(/^dh$/,@liveroles)) {
                   5027:                                         push(@possroles,$role);
                   5028:                                     } else {
                   5029:                                         next;
                   5030:                                     }
                   5031:                                 } elsif ($curraccess eq 'da') {
                   5032:                                     if (grep(/^da$/,@liveroles)) {
                   5033:                                         push(@possroles,$role);
                   5034:                                     } else {
                   5035:                                         next;
                   5036:                                     }
1.1172.2.89  raeburn  5037:                                 } elsif ($curraccess eq 'status') {
                   5038:                                     if (@okstatus) {
                   5039:                                         if (!@statuses) {
                   5040:                                             if (grep(/^default$/,@okstatus)) {
                   5041:                                                 push(@possroles,$role);
                   5042:                                             }
                   5043:                                         } else {
                   5044:                                             foreach my $status (@okstatus) {
                   5045:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5046:                                                     push(@possroles,$role);
                   5047:                                                     last;
                   5048:                                                 }
                   5049:                                             }
                   5050:                                         }
                   5051:                                     }
                   5052:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5053:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5054:                                         if ($curraccess eq 'exc') {
                   5055:                                             push(@possroles,$role);
                   5056:                                         }
                   5057:                                     } elsif ($curraccess eq 'inc') {
                   5058:                                         push(@possroles,$role);
                   5059:                                     }
                   5060:                                 }
                   5061:                             }
                   5062:                         }
                   5063:                     }
                   5064:                 }
                   5065:             }
                   5066:         }
                   5067:     }
                   5068:     unless (ref($description) eq 'HASH') {
                   5069:         if (ref($roles_by_num) eq 'ARRAY') {
                   5070:             my %desc;
                   5071:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5072:             $description = \%desc;
                   5073:         } else {
                   5074:             $description = {};
                   5075:         }
                   5076:     }
                   5077:     return (\@possroles,$description);
                   5078: }
                   5079: 
1.399     www      5080: # ----------------------------------------------------- Frontpage Announcements
                   5081: #
                   5082: #
                   5083: 
                   5084: sub postannounce {
                   5085:     my ($server,$text)=@_;
1.844     albertel 5086:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5087:     unless ($text=~/\w/) { $text=''; }
                   5088:     return &reply('setannounce:'.&escape($text),$server);
                   5089: }
                   5090: 
                   5091: sub getannounce {
1.448     albertel 5092: 
1.1172.2.96  raeburn  5093:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5094: 	my $announcement='';
1.800     albertel 5095: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5096: 	close($fh);
1.399     www      5097: 	if ($announcement=~/\w/) { 
                   5098: 	    return 
                   5099:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5100:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5101: 	} else {
                   5102: 	    return '';
                   5103: 	}
                   5104:     } else {
                   5105: 	return '';
                   5106:     }
1.351     www      5107: }
1.353     www      5108: 
                   5109: # ---------------------------------------------------------- Course ID routines
                   5110: # Deal with domain's nohist_courseid.db files
                   5111: #
                   5112: 
                   5113: sub courseidput {
1.921     raeburn  5114:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5115:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5116:     my $outcome;
                   5117:     if ($caller eq 'timeonly') {
                   5118:         my $cids = '';
                   5119:         foreach my $item (keys(%$storehash)) {
                   5120:             $cids.=&escape($item).'&';
                   5121:         }
                   5122:         $cids=~s/\&$//;
                   5123:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5124:                           $coursehome);       
                   5125:     } else {
                   5126:         my $items = '';
                   5127:         foreach my $item (keys(%$storehash)) {
                   5128:             $items.= &escape($item).'='.
                   5129:                      &freeze_escape($$storehash{$item}).'&';
                   5130:         }
                   5131:         $items=~s/\&$//;
                   5132:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5133:                           $coursehome);
1.918     raeburn  5134:     }
                   5135:     if ($outcome eq 'unknown_cmd') {
                   5136:         my $what;
                   5137:         foreach my $cid (keys(%$storehash)) {
                   5138:             $what .= &escape($cid).'=';
1.921     raeburn  5139:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5140:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5141:             }
                   5142:             $what =~ s/\:$/&/;
                   5143:         }
                   5144:         $what =~ s/\&$//;  
                   5145:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5146:     } else {
                   5147:         return $outcome;
                   5148:     }
1.353     www      5149: }
                   5150: 
                   5151: sub courseiddump {
1.921     raeburn  5152:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5153:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5154:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5155:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5156:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5157:     my $as_hash = 1;
                   5158:     my %returnhash;
                   5159:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5160:     my %libserv = &all_library();
                   5161:     foreach my $tryserver (keys(%libserv)) {
                   5162:         if ( (  $hostidflag == 1 
                   5163: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5164: 	     || (!defined($hostidflag)) ) {
                   5165: 
1.918     raeburn  5166: 	    if (($domfilter eq '') ||
                   5167: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5168:                 my $rep;
                   5169:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5170:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5171:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5172:                                 &escape($descfilter), &escape($instcodefilter),
                   5173:                                 &escape($ownerfilter), &escape($coursefilter),
                   5174:                                 &escape($typefilter), &escape($regexp_ok),
                   5175:                                 $as_hash, &escape($selfenrollonly),
                   5176:                                 &escape($catfilter), $showhidden, $caller,
                   5177:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5178:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5179:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5180:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5181:                 } else {
                   5182:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5183:                              $sincefilter.':'.&escape($descfilter).':'.
                   5184:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5185:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5186:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5187:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5188:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5189:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5190:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5191:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5192:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5193:                 }
                   5194: 
1.918     raeburn  5195:                 my @pairs=split(/\&/,$rep);
                   5196:                 foreach my $item (@pairs) {
                   5197:                     my ($key,$value)=split(/\=/,$item,2);
                   5198:                     $key = &unescape($key);
                   5199:                     next if ($key =~ /^error: 2 /);
                   5200:                     my $result = &thaw_unescape($value);
                   5201:                     if (ref($result) eq 'HASH') {
                   5202:                         $returnhash{$key}=$result;
                   5203:                     } else {
1.921     raeburn  5204:                         my @responses = split(/:/,$value);
                   5205:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5206:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5207:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5208:                         }
1.1008    raeburn  5209:                     }
1.353     www      5210:                 }
                   5211:             }
                   5212:         }
                   5213:     }
                   5214:     return %returnhash;
                   5215: }
                   5216: 
1.1055    raeburn  5217: sub courselastaccess {
                   5218:     my ($cdom,$cnum,$hostidref) = @_;
                   5219:     my %returnhash;
                   5220:     if ($cdom && $cnum) {
                   5221:         my $chome = &homeserver($cnum,$cdom);
                   5222:         if ($chome ne 'no_host') {
                   5223:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5224:             &extract_lastaccess(\%returnhash,$rep);
                   5225:         }
                   5226:     } else {
                   5227:         if (!$cdom) { $cdom=''; }
                   5228:         my %libserv = &all_library();
                   5229:         foreach my $tryserver (keys(%libserv)) {
                   5230:             if (ref($hostidref) eq 'ARRAY') {
                   5231:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5232:             } 
                   5233:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5234:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5235:                 &extract_lastaccess(\%returnhash,$rep);
                   5236:             }
                   5237:         }
                   5238:     }
                   5239:     return %returnhash;
                   5240: }
                   5241: 
                   5242: sub extract_lastaccess {
                   5243:     my ($returnhash,$rep) = @_;
                   5244:     if (ref($returnhash) eq 'HASH') {
                   5245:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5246:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5247:                  $rep eq '') {
                   5248:             my @pairs=split(/\&/,$rep);
                   5249:             foreach my $item (@pairs) {
                   5250:                 my ($key,$value)=split(/\=/,$item,2);
                   5251:                 $key = &unescape($key);
                   5252:                 next if ($key =~ /^error: 2 /);
                   5253:                 $returnhash->{$key} = &thaw_unescape($value);
                   5254:             }
                   5255:         }
                   5256:     }
                   5257:     return;
                   5258: }
                   5259: 
1.658     raeburn  5260: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5261: 
                   5262: sub dcmailput {
1.685     raeburn  5263:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5264:     my $status = &Apache::lonnet::critical(
1.740     www      5265:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5266:        &escape($message),$server);
1.662     raeburn  5267:     return $status;
                   5268: }
                   5269: 
1.658     raeburn  5270: sub dcmaildump {
                   5271:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5272:     my %returnhash=();
1.846     albertel 5273: 
                   5274:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5275:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5276:                                                          &escape($enddate).':';
                   5277: 	my @esc_senders=map { &escape($_)} @$senders;
                   5278: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5279: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5280:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5281:             if (($key) && ($value)) {
                   5282:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5283:             }
                   5284:         }
                   5285:     }
                   5286:     return %returnhash;
                   5287: }
1.662     raeburn  5288: # ---------------------------------------------------------- Domain roles
                   5289: 
                   5290: sub get_domain_roles {
                   5291:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5292:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5293:         $startdate = '.';
                   5294:     }
1.1018    raeburn  5295:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5296:         $enddate = '.';
                   5297:     }
1.922     raeburn  5298:     my $rolelist;
                   5299:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5300:         $rolelist = join('&',@{$roles});
1.922     raeburn  5301:     }
1.662     raeburn  5302:     my %personnel = ();
1.841     albertel 5303: 
                   5304:     my %servers = &get_servers($dom,'library');
                   5305:     foreach my $tryserver (keys(%servers)) {
                   5306: 	%{$personnel{$tryserver}}=();
                   5307: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5308: 					    &escape($startdate).':'.
                   5309: 					    &escape($enddate).':'.
                   5310: 					    &escape($rolelist), $tryserver))) {
                   5311: 	    my ($key,$value) = split(/\=/,$line,2);
                   5312: 	    if (($key) && ($value)) {
                   5313: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5314: 	    }
                   5315: 	}
1.662     raeburn  5316:     }
                   5317:     return %personnel;
                   5318: }
1.658     raeburn  5319: 
1.1172.2.89  raeburn  5320: sub get_active_domroles {
                   5321:     my ($dom,$roles) = @_;
                   5322:     return () unless (ref($roles) eq 'ARRAY');
                   5323:     my $now = time;
                   5324:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5325:     my %domroles;
                   5326:     foreach my $server (keys(%dompersonnel)) {
                   5327:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5328:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5329:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5330:         }
                   5331:     }
                   5332:     return %domroles;
                   5333: }
                   5334: 
1.1057    www      5335: # ----------------------------------------------------------- Interval timing 
1.149     www      5336: 
1.1153    www      5337: {
                   5338: # Caches needed for speedup of navmaps
                   5339: # We don't want to cache this for very long at all (5 seconds at most)
                   5340: # 
                   5341: # The user for whom we cache
                   5342: my $cachedkey='';
                   5343: # The cached times for this user
                   5344: my %cachedtimes=();
                   5345: # When this was last done
1.1172.2.66  raeburn  5346: my $cachedtime='';
1.1153    www      5347: 
                   5348: sub load_all_first_access {
1.1154    raeburn  5349:     my ($uname,$udom)=@_;
1.1156    www      5350:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5351:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5352:         return;
                   5353:     }
                   5354:     $cachedtime=time;
                   5355:     $cachedkey=$uname.':'.$udom;
                   5356:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5357: }
                   5358: 
1.504     albertel 5359: sub get_first_access {
1.1162    raeburn  5360:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5361:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5362:     if ($argsymb) { $symb=$argsymb; }
                   5363:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5364:     if ($argmap) { $map = $argmap; }
1.926     albertel 5365:     if ($type eq 'course') {
                   5366: 	$res='course';
                   5367:     } elsif ($type eq 'map') {
1.588     albertel 5368: 	$res=&symbread($map);
                   5369:     } else {
                   5370: 	$res=$symb;
                   5371:     }
1.1153    www      5372:     &load_all_first_access($uname,$udom);
                   5373:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5374: }
                   5375: 
                   5376: sub set_first_access {
1.1162    raeburn  5377:     my ($type,$interval)=@_;
1.790     albertel 5378:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5379:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5380:     if ($type eq 'course') {
                   5381: 	$res='course';
                   5382:     } elsif ($type eq 'map') {
1.588     albertel 5383: 	$res=&symbread($map);
                   5384:     } else {
                   5385: 	$res=$symb;
                   5386:     }
1.1153    www      5387:     $cachedkey='';
1.1162    raeburn  5388:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5389:     if ($firstaccess) {
                   5390:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5391:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5392:                  "in $courseid");
                   5393:         return 'already_set';
                   5394:     } else {
1.1162    raeburn  5395:         my $start = time;
                   5396: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5397:                           $udom,$uname);
                   5398:         if ($putres eq 'ok') {
                   5399:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5400:                  $udom,$uname); 
                   5401:             &appenv(
                   5402:                      {
                   5403:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5404:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5405:                      }
                   5406:                   );
1.1172.2.97  raeburn  5407:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5408:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5409:             }
1.1172.2.102  raeburn  5410:         } elsif ($putres ne 'refused') {
                   5411:             &logthis("Result: $putres when attempting to set first access time ".
                   5412:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5413:         }
                   5414:         return $putres;
1.505     albertel 5415:     }
                   5416:     return 'already_set';
1.504     albertel 5417: }
1.1153    www      5418: }
1.1172.2.32  raeburn  5419: 
                   5420: sub checkout {
                   5421:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5422:     my $now=time;
                   5423:     my $lonhost=$perlvar{'lonHostID'};
                   5424:     my $infostr=&escape(
                   5425:                  'CHECKOUTTOKEN&'.
                   5426:                  $tuname.'&'.
                   5427:                  $tudom.'&'.
                   5428:                  $tcrsid.'&'.
                   5429:                  $symb.'&'.
                   5430:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5431:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5432:     if ($token=~/^error\:/) {
                   5433:         &logthis("<font color=\"blue\">WARNING: ".
                   5434:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5435:                  "</font>");
                   5436:         return '';
                   5437:     }
                   5438: 
                   5439:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5440:     $token=~tr/a-z/A-Z/;
                   5441: 
                   5442:     my %infohash=('resource.0.outtoken' => $token,
                   5443:                   'resource.0.checkouttime' => $now,
                   5444:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5445: 
                   5446:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5447:        return '';
                   5448:     } else {
                   5449:         &logthis("<font color=\"blue\">WARNING: ".
                   5450:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5451:                  "</font>");
                   5452:     }
                   5453: 
                   5454:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5455:                          &escape('Checkout '.$infostr.' - '.
                   5456:                                                  $token)) ne 'ok') {
                   5457:         return '';
                   5458:     } else {
                   5459:         &logthis("<font color=\"blue\">WARNING: ".
                   5460:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5461:                  "</font>");
                   5462:     }
                   5463:     return $token;
                   5464: }
                   5465: 
                   5466: # ------------------------------------------------------------ Check in an item
                   5467: 
                   5468: sub checkin {
                   5469:     my $token=shift;
                   5470:     my $now=time;
                   5471:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5472:     $lonhost=~tr/A-Z/a-z/;
                   5473:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5474:     $dtoken=~s/\W/\_/g;
                   5475:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5476:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5477: 
                   5478:     unless (($tuname) && ($tudom)) {
                   5479:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5480:         return '';
                   5481:     }
                   5482: 
                   5483:     unless (&allowed('mgr',$tcrsid)) {
                   5484:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5485:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5486:         return '';
                   5487:     }
                   5488: 
                   5489:     my %infohash=('resource.0.intoken' => $token,
                   5490:                   'resource.0.checkintime' => $now,
                   5491:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5492: 
                   5493:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5494:        return '';
                   5495:     }
                   5496: 
                   5497:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5498:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5499:         return '';
                   5500:     }
                   5501: 
                   5502:     return ($symb,$tuname,$tudom,$tcrsid);
                   5503: }
                   5504: 
1.110     www      5505: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5506: 
                   5507: sub expirespread {
                   5508:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5509:     my $cid=$env{'request.course.id'}; 
1.110     www      5510:     if ($cid) {
                   5511:        my $now=time;
                   5512:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5513:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5514:                             $env{'course.'.$cid.'.num'}.
1.110     www      5515: 	        	    ':nohist_expirationdates:'.
                   5516:                             &escape($key).'='.$now,
1.620     albertel 5517:                             $env{'course.'.$cid.'.home'})
1.110     www      5518:     }
                   5519:     return 'ok';
1.14      www      5520: }
                   5521: 
1.109     www      5522: # ----------------------------------------------------- Devalidate Spreadsheets
                   5523: 
                   5524: sub devalidate {
1.325     www      5525:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5526:     my $cid=$env{'request.course.id'}; 
1.109     www      5527:     if ($cid) {
1.391     matthew  5528:         # delete the stored spreadsheets for
                   5529:         # - the student level sheet of this user in course's homespace
                   5530:         # - the assessment level sheet for this resource 
                   5531:         #   for this user in user's homespace
1.553     albertel 5532: 	# - current conditional state info
1.325     www      5533: 	my $key=$uname.':'.$udom.':';
1.109     www      5534:         my $status=
1.299     matthew  5535: 	    &del('nohist_calculatedsheets',
1.391     matthew  5536: 		 [$key.'studentcalc:'],
1.620     albertel 5537: 		 $env{'course.'.$cid.'.domain'},
                   5538: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5539: 		.' '.
                   5540: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5541: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5542:         unless ($status eq 'ok ok') {
                   5543:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5544:                     $uname.' at '.$udom.' for '.
1.109     www      5545: 		    $symb.': '.$status);
1.133     albertel 5546:         }
1.553     albertel 5547: 	&delenv('user.state.'.$cid);
1.109     www      5548:     }
                   5549: }
                   5550: 
1.265     albertel 5551: sub get_scalar {
                   5552:     my ($string,$end) = @_;
                   5553:     my $value;
                   5554:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5555: 	$value = $1;
                   5556:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5557: 	$value = $1;
                   5558:     }
                   5559:     return &unescape($value);
                   5560: }
                   5561: 
                   5562: sub array2str {
                   5563:   my (@array) = @_;
                   5564:   my $result=&arrayref2str(\@array);
                   5565:   $result=~s/^__ARRAY_REF__//;
                   5566:   $result=~s/__END_ARRAY_REF__$//;
                   5567:   return $result;
                   5568: }
                   5569: 
1.204     albertel 5570: sub arrayref2str {
                   5571:   my ($arrayref) = @_;
1.265     albertel 5572:   my $result='__ARRAY_REF__';
1.204     albertel 5573:   foreach my $elem (@$arrayref) {
1.265     albertel 5574:     if(ref($elem) eq 'ARRAY') {
                   5575:       $result.=&arrayref2str($elem).'&';
                   5576:     } elsif(ref($elem) eq 'HASH') {
                   5577:       $result.=&hashref2str($elem).'&';
                   5578:     } elsif(ref($elem)) {
                   5579:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5580:     } else {
                   5581:       $result.=&escape($elem).'&';
                   5582:     }
                   5583:   }
                   5584:   $result=~s/\&$//;
1.265     albertel 5585:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5586:   return $result;
                   5587: }
                   5588: 
1.168     albertel 5589: sub hash2str {
1.204     albertel 5590:   my (%hash) = @_;
                   5591:   my $result=&hashref2str(\%hash);
1.265     albertel 5592:   $result=~s/^__HASH_REF__//;
                   5593:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5594:   return $result;
                   5595: }
                   5596: 
                   5597: sub hashref2str {
                   5598:   my ($hashref)=@_;
1.265     albertel 5599:   my $result='__HASH_REF__';
1.800     albertel 5600:   foreach my $key (sort(keys(%$hashref))) {
                   5601:     if (ref($key) eq 'ARRAY') {
                   5602:       $result.=&arrayref2str($key).'=';
                   5603:     } elsif (ref($key) eq 'HASH') {
                   5604:       $result.=&hashref2str($key).'=';
                   5605:     } elsif (ref($key)) {
1.265     albertel 5606:       $result.='=';
1.800     albertel 5607:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5608:     } else {
1.1132    raeburn  5609: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5610:     }
                   5611: 
1.800     albertel 5612:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5613:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5614:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5615:       $result.=&hashref2str($hashref->{$key}).'&';
                   5616:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5617:        $result.='&';
1.800     albertel 5618:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5619:     } else {
1.800     albertel 5620:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5621:     }
                   5622:   }
1.168     albertel 5623:   $result=~s/\&$//;
1.265     albertel 5624:   $result .= '__END_HASH_REF__';
1.168     albertel 5625:   return $result;
                   5626: }
                   5627: 
                   5628: sub str2hash {
1.265     albertel 5629:     my ($string)=@_;
                   5630:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5631:     return %$hash;
                   5632: }
                   5633: 
                   5634: sub str2hashref {
1.168     albertel 5635:   my ($string) = @_;
1.265     albertel 5636: 
                   5637:   my %hash;
                   5638: 
                   5639:   if($string !~ /^__HASH_REF__/) {
                   5640:       if (! ($string eq '' || !defined($string))) {
                   5641: 	  $hash{'error'}='Not hash reference';
                   5642:       }
                   5643:       return (\%hash, $string);
                   5644:   }
                   5645: 
                   5646:   $string =~ s/^__HASH_REF__//;
                   5647: 
                   5648:   while($string !~ /^__END_HASH_REF__/) {
                   5649:       #key
                   5650:       my $key='';
                   5651:       if($string =~ /^__HASH_REF__/) {
                   5652:           ($key, $string)=&str2hashref($string);
                   5653:           if(defined($key->{'error'})) {
                   5654:               $hash{'error'}='Bad data';
                   5655:               return (\%hash, $string);
                   5656:           }
                   5657:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5658:           ($key, $string)=&str2arrayref($string);
                   5659:           if($key->[0] eq 'Array reference error') {
                   5660:               $hash{'error'}='Bad data';
                   5661:               return (\%hash, $string);
                   5662:           }
                   5663:       } else {
                   5664:           $string =~ s/^(.*?)=//;
1.267     albertel 5665: 	  $key=&unescape($1);
1.265     albertel 5666:       }
                   5667:       $string =~ s/^=//;
                   5668: 
                   5669:       #value
                   5670:       my $value='';
                   5671:       if($string =~ /^__HASH_REF__/) {
                   5672:           ($value, $string)=&str2hashref($string);
                   5673:           if(defined($value->{'error'})) {
                   5674:               $hash{'error'}='Bad data';
                   5675:               return (\%hash, $string);
                   5676:           }
                   5677:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5678:           ($value, $string)=&str2arrayref($string);
                   5679:           if($value->[0] eq 'Array reference error') {
                   5680:               $hash{'error'}='Bad data';
                   5681:               return (\%hash, $string);
                   5682:           }
                   5683:       } else {
                   5684: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5685:       }
                   5686:       $string =~ s/^&//;
                   5687: 
                   5688:       $hash{$key}=$value;
1.204     albertel 5689:   }
1.265     albertel 5690: 
                   5691:   $string =~ s/^__END_HASH_REF__//;
                   5692: 
                   5693:   return (\%hash, $string);
1.204     albertel 5694: }
                   5695: 
                   5696: sub str2array {
1.265     albertel 5697:     my ($string)=@_;
                   5698:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5699:     return @$array;
                   5700: }
                   5701: 
                   5702: sub str2arrayref {
1.204     albertel 5703:   my ($string) = @_;
1.265     albertel 5704:   my @array;
                   5705: 
                   5706:   if($string !~ /^__ARRAY_REF__/) {
                   5707:       if (! ($string eq '' || !defined($string))) {
                   5708: 	  $array[0]='Array reference error';
                   5709:       }
                   5710:       return (\@array, $string);
                   5711:   }
                   5712: 
                   5713:   $string =~ s/^__ARRAY_REF__//;
                   5714: 
                   5715:   while($string !~ /^__END_ARRAY_REF__/) {
                   5716:       my $value='';
                   5717:       if($string =~ /^__HASH_REF__/) {
                   5718:           ($value, $string)=&str2hashref($string);
                   5719:           if(defined($value->{'error'})) {
                   5720:               $array[0] ='Array reference error';
                   5721:               return (\@array, $string);
                   5722:           }
                   5723:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5724:           ($value, $string)=&str2arrayref($string);
                   5725:           if($value->[0] eq 'Array reference error') {
                   5726:               $array[0] ='Array reference error';
                   5727:               return (\@array, $string);
                   5728:           }
                   5729:       } else {
                   5730: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5731:       }
                   5732:       $string =~ s/^&//;
                   5733: 
                   5734:       push(@array, $value);
1.191     harris41 5735:   }
1.265     albertel 5736: 
                   5737:   $string =~ s/^__END_ARRAY_REF__//;
                   5738: 
                   5739:   return (\@array, $string);
1.168     albertel 5740: }
                   5741: 
1.167     albertel 5742: # -------------------------------------------------------------------Temp Store
                   5743: 
1.168     albertel 5744: sub tmpreset {
                   5745:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5746:   if (!$symb) {
                   5747:     $symb=&symbread();
1.620     albertel 5748:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5749:   }
                   5750:   $symb=escape($symb);
                   5751: 
1.620     albertel 5752:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5753:   $namespace=~s/\//\_/g;
                   5754:   $namespace=~s/\W//g;
                   5755: 
1.620     albertel 5756:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5757:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5758:   if ($domain eq 'public' && $stuname eq 'public') {
                   5759:       $stuname=$ENV{'REMOTE_ADDR'};
                   5760:   }
1.1117    foxr     5761:   my $path=LONCAPA::tempdir();
1.168     albertel 5762:   my %hash;
                   5763:   if (tie(%hash,'GDBM_File',
                   5764: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5765: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5766:     foreach my $key (keys(%hash)) {
1.180     albertel 5767:       if ($key=~ /:$symb/) {
1.168     albertel 5768: 	delete($hash{$key});
                   5769:       }
                   5770:     }
                   5771:   }
                   5772: }
                   5773: 
1.167     albertel 5774: sub tmpstore {
1.168     albertel 5775:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5776: 
                   5777:   if (!$symb) {
                   5778:     $symb=&symbread();
1.620     albertel 5779:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5780:   }
                   5781:   $symb=escape($symb);
                   5782: 
                   5783:   if (!$namespace) {
                   5784:     # I don't think we would ever want to store this for a course.
                   5785:     # it seems this will only be used if we don't have a course.
1.620     albertel 5786:     #$namespace=$env{'request.course.id'};
1.168     albertel 5787:     #if (!$namespace) {
1.620     albertel 5788:       $namespace=$env{'request.state'};
1.168     albertel 5789:     #}
                   5790:   }
                   5791:   $namespace=~s/\//\_/g;
                   5792:   $namespace=~s/\W//g;
1.620     albertel 5793:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5794:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5795:   if ($domain eq 'public' && $stuname eq 'public') {
                   5796:       $stuname=$ENV{'REMOTE_ADDR'};
                   5797:   }
1.168     albertel 5798:   my $now=time;
                   5799:   my %hash;
1.1117    foxr     5800:   my $path=LONCAPA::tempdir();
1.168     albertel 5801:   if (tie(%hash,'GDBM_File',
                   5802: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5803: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5804:     $hash{"version:$symb"}++;
                   5805:     my $version=$hash{"version:$symb"};
                   5806:     my $allkeys=''; 
                   5807:     foreach my $key (keys(%$storehash)) {
                   5808:       $allkeys.=$key.':';
1.591     albertel 5809:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5810:     }
                   5811:     $hash{"$version:$symb:timestamp"}=$now;
                   5812:     $allkeys.='timestamp';
                   5813:     $hash{"$version:keys:$symb"}=$allkeys;
                   5814:     if (untie(%hash)) {
                   5815:       return 'ok';
                   5816:     } else {
                   5817:       return "error:$!";
                   5818:     }
                   5819:   } else {
                   5820:     return "error:$!";
                   5821:   }
                   5822: }
1.167     albertel 5823: 
1.168     albertel 5824: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5825: 
1.168     albertel 5826: sub tmprestore {
                   5827:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5828: 
1.168     albertel 5829:   if (!$symb) {
                   5830:     $symb=&symbread();
1.620     albertel 5831:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5832:   }
                   5833:   $symb=escape($symb);
                   5834: 
1.620     albertel 5835:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5836: 
1.620     albertel 5837:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5838:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5839:   if ($domain eq 'public' && $stuname eq 'public') {
                   5840:       $stuname=$ENV{'REMOTE_ADDR'};
                   5841:   }
1.168     albertel 5842:   my %returnhash;
                   5843:   $namespace=~s/\//\_/g;
                   5844:   $namespace=~s/\W//g;
                   5845:   my %hash;
1.1117    foxr     5846:   my $path=LONCAPA::tempdir();
1.168     albertel 5847:   if (tie(%hash,'GDBM_File',
                   5848: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5849: 	  &GDBM_READER(),0640)) {
1.168     albertel 5850:     my $version=$hash{"version:$symb"};
                   5851:     $returnhash{'version'}=$version;
                   5852:     my $scope;
                   5853:     for ($scope=1;$scope<=$version;$scope++) {
                   5854:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5855:       my @keys=split(/:/,$vkeys);
                   5856:       my $key;
                   5857:       $returnhash{"$scope:keys"}=$vkeys;
                   5858:       foreach $key (@keys) {
1.591     albertel 5859: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5860: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5861:       }
                   5862:     }
1.168     albertel 5863:     if (!(untie(%hash))) {
                   5864:       return "error:$!";
                   5865:     }
                   5866:   } else {
                   5867:     return "error:$!";
                   5868:   }
                   5869:   return %returnhash;
1.167     albertel 5870: }
                   5871: 
1.9       www      5872: # ----------------------------------------------------------------------- Store
                   5873: 
                   5874: sub store {
1.1172.2.64  raeburn  5875:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5876:     my $home='';
                   5877: 
1.168     albertel 5878:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5879: 
1.213     www      5880:     $symb=&symbclean($symb);
1.122     albertel 5881:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5882: 
1.620     albertel 5883:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5884:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5885: 
                   5886:     &devalidate($symb,$stuname,$domain);
1.109     www      5887: 
                   5888:     $symb=escape($symb);
1.187     www      5889:     if (!$namespace) { 
1.620     albertel 5890:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5891:           return ''; 
                   5892:        } 
                   5893:     }
1.620     albertel 5894:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5895: 
                   5896:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5897:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5898: 
1.12      www      5899:     my $namevalue='';
1.800     albertel 5900:     foreach my $key (keys(%$storehash)) {
                   5901:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5902:     }
1.12      www      5903:     $namevalue=~s/\&$//;
1.187     www      5904:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5905:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5906: }
                   5907: 
1.47      www      5908: # -------------------------------------------------------------- Critical Store
                   5909: 
                   5910: sub cstore {
1.1172.2.64  raeburn  5911:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5912:     my $home='';
                   5913: 
1.168     albertel 5914:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5915: 
1.213     www      5916:     $symb=&symbclean($symb);
1.122     albertel 5917:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5918: 
1.620     albertel 5919:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5920:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5921: 
                   5922:     &devalidate($symb,$stuname,$domain);
1.109     www      5923: 
                   5924:     $symb=escape($symb);
1.187     www      5925:     if (!$namespace) { 
1.620     albertel 5926:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5927:           return ''; 
                   5928:        } 
                   5929:     }
1.620     albertel 5930:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5931: 
                   5932:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5933:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5934: 
1.47      www      5935:     my $namevalue='';
1.800     albertel 5936:     foreach my $key (keys(%$storehash)) {
                   5937:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5938:     }
1.47      www      5939:     $namevalue=~s/\&$//;
1.187     www      5940:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5941:     return critical
1.1172.2.64  raeburn  5942:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5943: }
                   5944: 
1.9       www      5945: # --------------------------------------------------------------------- Restore
                   5946: 
                   5947: sub restore {
1.124     www      5948:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5949:     my $home='';
                   5950: 
1.168     albertel 5951:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5952: 
1.122     albertel 5953:     if (!$symb) {
1.1172.2.26  raeburn  5954:         return if ($namespace eq 'courserequests');
                   5955:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5956:     } else {
1.1172.2.26  raeburn  5957:         unless ($namespace eq 'courserequests') {
                   5958:             $symb=&escape(&symbclean($symb));
                   5959:         }
1.122     albertel 5960:     }
1.188     www      5961:     if (!$namespace) { 
1.620     albertel 5962:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5963:           return ''; 
                   5964:        } 
                   5965:     }
1.620     albertel 5966:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5967:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5968:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5969:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5970: 
1.12      www      5971:     my %returnhash=();
1.800     albertel 5972:     foreach my $line (split(/\&/,$answer)) {
                   5973: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5974:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5975:     }
1.75      www      5976:     my $version;
                   5977:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5978:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5979:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5980:        }
1.75      www      5981:     }
1.13      www      5982:     return %returnhash;
1.34      www      5983: }
                   5984: 
                   5985: # ---------------------------------------------------------- Course Description
1.1118    foxr     5986: #
                   5987: #  
1.34      www      5988: 
                   5989: sub coursedescription {
1.731     albertel 5990:     my ($courseid,$args)=@_;
1.34      www      5991:     $courseid=~s/^\///;
1.49      www      5992:     $courseid=~s/\_/\//g;
1.34      www      5993:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5994:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5995:     my $normalid=$cdomain.'_'.$cnum;
                   5996:     # need to always cache even if we get errors otherwise we keep 
                   5997:     # trying and trying and trying to get the course description.
                   5998:     my %envhash=();
                   5999:     my %returnhash=();
1.731     albertel 6000:     
                   6001:     my $expiretime=600;
                   6002:     if ($env{'request.course.id'} eq $normalid) {
                   6003: 	$expiretime=120;
                   6004:     }
                   6005: 
                   6006:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6007:     if (!$args->{'freshen_cache'}
                   6008: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6009: 	foreach my $key (keys(%env)) {
                   6010: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6011: 	    my ($setting) = $1;
                   6012: 	    $returnhash{$setting} = $env{$key};
                   6013: 	}
                   6014: 	return %returnhash;
                   6015:     }
                   6016: 
1.1118    foxr     6017:     # get the data again
                   6018: 
1.731     albertel 6019:     if (!$args->{'one_time'}) {
                   6020: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6021:     }
1.811     albertel 6022: 
1.34      www      6023:     if ($chome ne 'no_host') {
1.302     albertel 6024:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6025:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6026: 	   my $username = $env{'user.name'}; # Defult username
                   6027: 	   if(defined $args->{'user'}) {
                   6028: 	       $username = $args->{'user'};
                   6029: 	   }
1.129     albertel 6030:            $returnhash{'home'}= $chome;
                   6031: 	   $returnhash{'domain'} = $cdomain;
                   6032: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6033:            if (!defined($returnhash{'type'})) {
                   6034:                $returnhash{'type'} = 'Course';
                   6035:            }
1.130     albertel 6036:            while (my ($name,$value) = each %returnhash) {
1.53      www      6037:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6038:            }
1.270     www      6039:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6040:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6041: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6042:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6043:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6044:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6045:        }
                   6046:     }
1.731     albertel 6047:     if (!$args->{'one_time'}) {
1.949     raeburn  6048: 	&appenv(\%envhash);
1.731     albertel 6049:     }
1.302     albertel 6050:     return %returnhash;
1.461     www      6051: }
                   6052: 
1.1080    raeburn  6053: sub update_released_required {
                   6054:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6055:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6056:         $cid = $env{'request.course.id'};
                   6057:         $cdom = $env{'course.'.$cid.'.domain'};
                   6058:         $cnum = $env{'course.'.$cid.'.num'};
                   6059:         $chome = $env{'course.'.$cid.'.home'};
                   6060:     }
                   6061:     if ($needsrelease) {
                   6062:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6063:         my $needsupdate;
                   6064:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6065:             $needsupdate = 1;
                   6066:         } else {
                   6067:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6068:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6069:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6070:                 $needsupdate = 1;
                   6071:             }
                   6072:         }
                   6073:         if ($needsupdate) {
                   6074:             my %needshash = (
                   6075:                              'internal.releaserequired' => $needsrelease,
                   6076:                             );
                   6077:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6078:             if ($putresult eq 'ok') {
                   6079:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6080:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6081:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6082:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6083:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6084:                 }
                   6085:             }
                   6086:         }
                   6087:     }
                   6088:     return;
                   6089: }
                   6090: 
1.461     www      6091: # -------------------------------------------------See if a user is privileged
                   6092: 
                   6093: sub privileged {
1.1172.2.23  raeburn  6094:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6095:     my $now = time;
1.1172.2.23  raeburn  6096:     my $roles;
                   6097:     if (ref($possroles) eq 'ARRAY') {
                   6098:         $roles = $possroles;
                   6099:     } else {
                   6100:         $roles = ['dc','su'];
                   6101:     }
                   6102:     if (ref($possdomains) eq 'ARRAY') {
                   6103:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6104:         foreach my $dom (@{$possdomains}) {
                   6105:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6106:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6107:                 foreach my $role (@{$roles}) {
                   6108:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6109:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6110:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6111:                             return 1 unless (($end && $end < $now) ||
                   6112:                                              ($start && $start > $now));
                   6113:                         }
                   6114:                     }
                   6115:                 }
                   6116:             }
                   6117:         }
                   6118:     } else {
                   6119:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6120:         my $now = time;
1.1170    droeschl 6121: 
1.1172.2.58  raeburn  6122:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6123:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6124:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6125:                 return 1 unless ($tend && $tend < $now)
                   6126:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6127:             }
1.1172.2.23  raeburn  6128:         }
                   6129:     }
1.461     www      6130:     return 0;
1.9       www      6131: }
1.1       albertel 6132: 
1.1172.2.23  raeburn  6133: sub privileged_by_domain {
                   6134:     my ($domains,$roles) = @_;
                   6135:     my %privileged = ();
                   6136:     my $cachetime = 60*60*24;
                   6137:     my $now = time;
                   6138:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6139:         return %privileged;
                   6140:     }
                   6141:     foreach my $dom (@{$domains}) {
                   6142:         next if (ref($privileged{$dom}) eq 'HASH');
                   6143:         my $needroles;
                   6144:         foreach my $role (@{$roles}) {
                   6145:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6146:             if (defined($cached)) {
                   6147:                 if (ref($result) eq 'HASH') {
                   6148:                     $privileged{$dom}{$role} = $result;
                   6149:                 }
                   6150:             } else {
                   6151:                 $needroles = 1;
                   6152:             }
                   6153:         }
                   6154:         if ($needroles) {
                   6155:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6156:             $privileged{$dom} = {};
                   6157:             foreach my $server (keys(%dompersonnel)) {
                   6158:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6159:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6160:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6161:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6162:                         next if ($end && $end < $now);
                   6163:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6164:                             $dompersonnel{$server}{$item};
                   6165:                     }
                   6166:                 }
                   6167:             }
                   6168:             if (ref($privileged{$dom}) eq 'HASH') {
                   6169:                 foreach my $role (@{$roles}) {
                   6170:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6171:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6172:                     } else {
                   6173:                         my %hash = ();
                   6174:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6175:                     }
                   6176:                 }
                   6177:             }
                   6178:         }
                   6179:     }
                   6180:     return %privileged;
                   6181: }
                   6182: 
1.103     harris41 6183: # -------------------------------------------------------- Get user privileges
1.11      www      6184: 
                   6185: sub rolesinit {
1.1169    droeschl 6186:     my ($domain, $username) = @_;
                   6187:     my %userroles = ('user.login.time' => time);
                   6188:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6189: 
                   6190:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6191:     # also, blocking can be triggered by an activating timer
                   6192:     # it's saved in the user's %env.
                   6193:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6194:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6195:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6196:         %timerintchk, %timerintenv);
                   6197: 
1.1162    raeburn  6198:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6199:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6200:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6201:     }
1.1169    droeschl 6202: 
1.1162    raeburn  6203:     foreach my $key (keys(%timerinterval)) {
                   6204:         my ($cid,$rest) = split(/\0/,$key);
                   6205:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6206:     }
1.1169    droeschl 6207: 
1.11      www      6208:     my %allroles=();
1.1162    raeburn  6209:     my %allgroups=();
1.11      www      6210: 
1.1172.2.58  raeburn  6211:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6212:         my $role = $rolesdump{$area};
                   6213:         $area =~ s/\_\w\w$//;
                   6214: 
                   6215:         my ($trole, $tend, $tstart, $group_privs);
                   6216: 
                   6217:         if ($role =~ /^cr/) {
                   6218:         # Custom role, defined by a user 
                   6219:         # e.g., user.role.cr/msu/smith/mynewrole
                   6220:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6221:                 $trole = $1;
                   6222:                 ($tend, $tstart) = split('_', $2);
                   6223:             } else {
                   6224:                 $trole = $role;
                   6225:             }
                   6226:         } elsif ($role =~ m|^gr/|) {
                   6227:         # Role of member in a group, defined within a course/community
                   6228:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6229:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6230:             next if $tstart eq '-1';
                   6231:             ($trole, $group_privs) = split(/\//, $trole);
                   6232:             $group_privs = &unescape($group_privs);
                   6233:         } else {
                   6234:         # Just a normal role, defined in roles.tab
                   6235:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6236:         }
                   6237: 
                   6238:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6239:                  $username);
                   6240:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6241: 
                   6242:         # role expired or not available yet?
                   6243:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6244:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6245: 
                   6246:         next if $area eq '' or $trole eq '';
                   6247: 
                   6248:         my $spec = "$trole.$area";
                   6249:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6250: 
                   6251:         if ($trole =~ /^cr\//) {
                   6252:         # Custom role, defined by a user
                   6253:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6254:         } elsif ($trole eq 'gr') {
                   6255:         # Role of a member in a group, defined within a course/community
                   6256:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6257:             next;
                   6258:         } else {
                   6259:         # Normal role, defined in roles.tab
                   6260:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6261:         }
                   6262: 
                   6263:         my $cid = $tdomain.'_'.$trest;
                   6264:         unless ($firstaccchk{$cid}) {
                   6265:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6266:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6267:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6268:                         $coursetimerstarts{$cid}{$item}; 
                   6269:                 }
                   6270:             }
                   6271:             $firstaccchk{$cid} = 1;
                   6272:         }
                   6273:         unless ($timerintchk{$cid}) {
                   6274:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6275:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6276:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6277:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6278:                 }
1.12      www      6279:             }
1.1169    droeschl 6280:             $timerintchk{$cid} = 1;
1.191     harris41 6281:         }
1.11      www      6282:     }
1.1169    droeschl 6283: 
1.1172.2.91  raeburn  6284:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6285:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6286:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6287:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6288: 
1.1162    raeburn  6289:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6290: }
                   6291: 
1.567     raeburn  6292: sub set_arearole {
1.1172.2.19  raeburn  6293:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6294:     unless ($nolog) {
1.567     raeburn  6295: # log the associated role with the area
1.1172.2.19  raeburn  6296:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6297:     }
1.743     albertel 6298:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6299: }
                   6300: 
                   6301: sub custom_roleprivs {
                   6302:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6303:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6304:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6305:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6306:         my ($rdummy,$roledef)=
                   6307:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6308:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6309:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6310:             if (defined($syspriv)) {
1.1043    raeburn  6311:                 if ($trest =~ /^$match_community$/) {
                   6312:                     $syspriv =~ s/bre\&S//; 
                   6313:                 }
1.567     raeburn  6314:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6315:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6316:             }
                   6317:             if ($tdomain ne '') {
                   6318:                 if (defined($dompriv)) {
                   6319:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6320:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6321:                 }
                   6322:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6323:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6324:                         my $rolename = $1;
                   6325:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6326:                     }
1.567     raeburn  6327:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6328:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6329:                 }
                   6330:             }
                   6331:         }
                   6332:     }
                   6333: }
                   6334: 
1.1172.2.89  raeburn  6335: sub course_adhocrole_privs {
                   6336:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6337:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6338:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6339:         my (%currprivs,%storeprivs);
                   6340:         foreach my $item (split(/:/,$coursepriv)) {
                   6341:             my ($priv,$restrict) = split(/\&/,$item);
                   6342:             $currprivs{$priv} = $restrict;
                   6343:         }
                   6344:         my (%possadd,%possremove,%full);
                   6345:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6346:             my ($priv,$restrict)=split(/\&/,$item);
                   6347:             $full{$priv} = $restrict;
                   6348:         }
                   6349:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6350:              next if ($item eq '');
                   6351:              my ($rule,$rest) = split(/=/,$item);
                   6352:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6353:              foreach my $priv (split(/:/,$rest)) {
                   6354:                  if ($priv ne '') {
                   6355:                      if ($rule eq 'off') {
                   6356:                          $possremove{$priv} = 1;
                   6357:                      } else {
                   6358:                          $possadd{$priv} = 1;
                   6359:                      }
                   6360:                  }
                   6361:              }
                   6362:          }
                   6363:          foreach my $priv (sort(keys(%full))) {
                   6364:              if (exists($currprivs{$priv})) {
                   6365:                  unless (exists($possremove{$priv})) {
                   6366:                      $storeprivs{$priv} = $currprivs{$priv};
                   6367:                  }
                   6368:              } elsif (exists($possadd{$priv})) {
                   6369:                  $storeprivs{$priv} = $full{$priv};
                   6370:              }
                   6371:          }
                   6372:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6373:      }
                   6374:      return $coursepriv;
                   6375: }
                   6376: 
1.678     raeburn  6377: sub group_roleprivs {
                   6378:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6379:     my $access = 1;
                   6380:     my $now = time;
                   6381:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6382:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6383:     if ($access) {
1.811     albertel 6384:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6385:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6386:     }
                   6387: }
1.567     raeburn  6388: 
                   6389: sub standard_roleprivs {
                   6390:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6391:     if (defined($pr{$trole.':s'})) {
                   6392:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6393:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6394:     }
                   6395:     if ($tdomain ne '') {
                   6396:         if (defined($pr{$trole.':d'})) {
                   6397:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6398:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6399:         }
                   6400:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6401:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6402:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6403:         }
                   6404:     }
                   6405: }
                   6406: 
                   6407: sub set_userprivs {
1.1064    raeburn  6408:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6409:     my $author=0;
                   6410:     my $adv=0;
1.1172.2.91  raeburn  6411:     my $rar=0;
1.678     raeburn  6412:     my %grouproles = ();
                   6413:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6414:         my @groupkeys; 
1.1000    raeburn  6415:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6416:             push(@groupkeys,$role);
                   6417:         }
                   6418:         if (ref($groups_roles) eq 'HASH') {
                   6419:             foreach my $key (keys(%{$groups_roles})) {
                   6420:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6421:                     push(@groupkeys,$key);
                   6422:                 }
                   6423:             }
                   6424:         }
                   6425:         if (@groupkeys > 0) {
                   6426:             foreach my $role (@groupkeys) {
                   6427:                 my ($trole,$area,$sec,$extendedarea);
                   6428:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6429:                     $trole = $1;
                   6430:                     $area = $2;
                   6431:                     $sec = $3;
                   6432:                     $extendedarea = $area.$sec;
                   6433:                     if (exists($$allgroups{$area})) {
                   6434:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6435:                             my $spec = $trole.'.'.$extendedarea;
                   6436:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6437:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6438:                         }
1.678     raeburn  6439:                     }
                   6440:                 }
                   6441:             }
                   6442:         }
                   6443:     }
1.800     albertel 6444:     foreach my $group (keys(%grouproles)) {
                   6445:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6446:     }
1.800     albertel 6447:     foreach my $role (keys(%{$allroles})) {
                   6448:         my %thesepriv;
1.941     raeburn  6449:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6450:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6451:             if ($item ne '') {
                   6452:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6453:                 if ($restrictions eq '') {
                   6454:                     $thesepriv{$privilege}='F';
                   6455:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6456:                     $thesepriv{$privilege}.=$restrictions;
                   6457:                 }
                   6458:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6459:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6460:             }
                   6461:         }
                   6462:         my $thesestr='';
1.1104    raeburn  6463:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6464: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6465: 	}
                   6466:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6467:     }
1.1172.2.91  raeburn  6468:     return ($author,$adv,$rar);
1.567     raeburn  6469: }
                   6470: 
1.994     raeburn  6471: sub role_status {
1.1104    raeburn  6472:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6473:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6474:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6475:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6476:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6477:             $$where = '/'.$two;
1.994     raeburn  6478:             $$trolecode=$$role.'.'.$$where;
                   6479:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6480:             $$tstatus='is';
1.1104    raeburn  6481:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6482:                 $$tstatus='future';
1.1034    raeburn  6483:                 if ($$tstart<$now) {
                   6484:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6485:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6486:                             my (%allroles,%allgroups,$group_privs,
                   6487:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6488:                             my %userroles = (
                   6489:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6490:                             );
1.1064    raeburn  6491:                             @rolecodes = ('cm'); 
1.1002    raeburn  6492:                             my $spec=$$role.'.'.$$where;
                   6493:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6494:                             if ($$role =~ /^cr\//) {
                   6495:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6496:                                 push(@rolecodes,'cr');
1.1002    raeburn  6497:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6498:                                 push(@rolecodes,$$role);
1.1002    raeburn  6499:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6500:                                                     $env{'user.name'});
1.1064    raeburn  6501:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6502:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6503:                                 $group_privs = &unescape($group_privs);
                   6504:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6505:                                 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  6506:                                 &get_groups_roles($tdomain,$trest,
                   6507:                                                   \%course_roles,\@rolecodes,
                   6508:                                                   \%groups_roles);
1.1002    raeburn  6509:                             } else {
1.1064    raeburn  6510:                                 push(@rolecodes,$$role);
1.1002    raeburn  6511:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6512:                             }
1.1172.2.91  raeburn  6513:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6514:                                                                    \%groups_roles);
1.1064    raeburn  6515:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6516:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6517:                         }
                   6518:                     }
1.1034    raeburn  6519:                     $$tstatus = 'is';
1.1002    raeburn  6520:                 }
1.994     raeburn  6521:             }
                   6522:             if ($$tend) {
1.1104    raeburn  6523:                 if ($$tend<$update) {
1.994     raeburn  6524:                     $$tstatus='expired';
                   6525:                 } elsif ($$tend<$now) {
                   6526:                     $$tstatus='will_not';
                   6527:                 }
                   6528:             }
                   6529:         }
                   6530:     }
                   6531: }
                   6532: 
1.1104    raeburn  6533: sub get_groups_roles {
                   6534:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6535:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6536:                   (ref($rolecodes) eq 'ARRAY') && 
                   6537:                   (ref($groups_roles) eq 'HASH')); 
                   6538:     if (keys(%{$cdom_courseroles}) > 0) {
                   6539:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6540:         if ($cdom ne '' && $cnum ne '') {
                   6541:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6542:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6543:                     my $crsrole = $1;
                   6544:                     my $crssec = $2;
                   6545:                     if ($crsrole =~ /^cr/) {
                   6546:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6547:                             push(@{$rolecodes},'cr');
                   6548:                         }
                   6549:                     } else {
                   6550:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6551:                             push(@{$rolecodes},$crsrole);
                   6552:                         }
                   6553:                     }
                   6554:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6555:                     if ($crssec ne '') {
                   6556:                         $rolekey .= "/$crssec";
                   6557:                     }
                   6558:                     $rolekey .= './';
                   6559:                     $groups_roles->{$rolekey} = $rolecodes;
                   6560:                 }
                   6561:             }
                   6562:         }
                   6563:     }
                   6564:     return;
                   6565: }
                   6566: 
                   6567: sub delete_env_groupprivs {
                   6568:     my ($where,$courseroles,$possroles) = @_;
                   6569:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6570:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6571:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6572:         %{$courseroles->{$udom}} =
                   6573:             &get_my_roles('','','userroles',['active'],
                   6574:                           $possroles,[$udom],1);
                   6575:     }
                   6576:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6577:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6578:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6579:             my $area = '/'.$cdom.'/'.$cnum;
                   6580:             my $privkey = "user.priv.$crsrole.$area";
                   6581:             if ($crssec ne '') {
                   6582:                 $privkey .= '/'.$crssec;
                   6583:             }
                   6584:             $privkey .= ".$area/$group";
                   6585:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6586:         }
                   6587:     }
                   6588:     return;
                   6589: }
                   6590: 
1.994     raeburn  6591: sub check_adhoc_privs {
1.1172.2.86  raeburn  6592:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6593:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6594:     if ($sec) {
                   6595:         $cckey .= '/'.$sec;
                   6596:     }
1.1172.2.9  raeburn  6597:     my $setprivs;
1.994     raeburn  6598:     if ($env{$cckey}) {
                   6599:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6600:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6601:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6602:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6603:             $setprivs = 1;
1.994     raeburn  6604:         }
                   6605:     } else {
1.1172.2.87  raeburn  6606:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6607:         $setprivs = 1;
1.994     raeburn  6608:     }
1.1172.2.9  raeburn  6609:     return $setprivs;
1.994     raeburn  6610: }
                   6611: 
                   6612: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6613: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6614:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6615:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6616:     if ($sec ne '') {
                   6617:         $area .= '/'.$sec;
                   6618:     }
1.994     raeburn  6619:     my $spec = $role.'.'.$area;
                   6620:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6621:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6622:     my %rolehash = ();
1.1172.2.89  raeburn  6623:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6624:         my $rolename = $1;
1.1172.2.84  raeburn  6625:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6626:         my %domdef = &get_domain_defaults($dcdom);
                   6627:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6628:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6629:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6630:             }
                   6631:         }
1.1172.2.84  raeburn  6632:     } else {
                   6633:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6634:     }
1.1172.2.91  raeburn  6635:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6636:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6637:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6638:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6639:         &appenv( {'request.role'        => $spec,
                   6640:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6641:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6642:                  }
                   6643:                );
                   6644:         my $tadv=0;
                   6645:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6646:         &appenv({'request.role.adv'    => $tadv});
                   6647:     }
1.994     raeburn  6648: }
                   6649: 
1.12      www      6650: # --------------------------------------------------------------- get interface
                   6651: 
                   6652: sub get {
1.131     albertel 6653:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6654:    my $items='';
1.800     albertel 6655:    foreach my $item (@$storearr) {
                   6656:        $items.=&escape($item).'&';
1.191     harris41 6657:    }
1.12      www      6658:    $items=~s/\&$//;
1.620     albertel 6659:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6660:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6661:    my $uhome=&homeserver($uname,$udomain);
                   6662: 
1.133     albertel 6663:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6664:    my @pairs=split(/\&/,$rep);
1.273     albertel 6665:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6666:      return @pairs;
                   6667:    }
1.15      www      6668:    my %returnhash=();
1.42      www      6669:    my $i=0;
1.800     albertel 6670:    foreach my $item (@$storearr) {
                   6671:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6672:       $i++;
1.191     harris41 6673:    }
1.15      www      6674:    return %returnhash;
1.27      www      6675: }
                   6676: 
                   6677: # --------------------------------------------------------------- del interface
                   6678: 
                   6679: sub del {
1.133     albertel 6680:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6681:    my $items='';
1.800     albertel 6682:    foreach my $item (@$storearr) {
                   6683:        $items.=&escape($item).'&';
1.191     harris41 6684:    }
1.984     neumanie 6685: 
1.27      www      6686:    $items=~s/\&$//;
1.620     albertel 6687:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6688:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6689:    my $uhome=&homeserver($uname,$udomain);
                   6690:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6691: }
                   6692: 
                   6693: # -------------------------------------------------------------- dump interface
                   6694: 
1.1172.2.22  raeburn  6695: sub unserialize {
                   6696:     my ($rep, $escapedkeys) = @_;
                   6697: 
                   6698:     return {} if $rep =~ /^error/;
                   6699: 
                   6700:     my %returnhash=();
                   6701:     foreach my $item (split(/\&/,$rep)) {
                   6702:         my ($key, $value) = split(/=/, $item, 2);
                   6703:         $key = unescape($key) unless $escapedkeys;
                   6704:         next if $key =~ /^error: 2 /;
                   6705:         $returnhash{$key} = &thaw_unescape($value);
                   6706:     }
                   6707:     return \%returnhash;
                   6708: }
                   6709: 
                   6710: # see Lond::dump_with_regexp
                   6711: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6712: sub dump {
1.1172.2.22  raeburn  6713:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6714:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6715:     if (!$uname) { $uname=$env{'user.name'}; }
                   6716:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6717: 
1.1172.2.55  raeburn  6718:     if ($regexp) {
                   6719:         $regexp=&escape($regexp);
                   6720:     } else {
                   6721:         $regexp='.';
                   6722:     }
1.1172.2.22  raeburn  6723:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6724:         # user is hosted on this machine
1.1172.2.55  raeburn  6725:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6726:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6727:         return %{&unserialize($reply, $escapedkeys)};
                   6728:     }
1.1166    raeburn  6729:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6730:     my @pairs=split(/\&/,$rep);
                   6731:     my %returnhash=();
1.1098    foxr     6732:     if (!($rep =~ /^error/ )) {
                   6733: 	foreach my $item (@pairs) {
                   6734: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6735:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6736: 	    next if ($key =~ /^error: 2 /);
                   6737: 	    $returnhash{$key}=&thaw_unescape($value);
                   6738: 	}
1.755     albertel 6739:     }
                   6740:     return %returnhash;
1.407     www      6741: }
                   6742: 
1.1098    foxr     6743: 
1.717     albertel 6744: # --------------------------------------------------------- dumpstore interface
                   6745: 
                   6746: sub dumpstore {
                   6747:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6748:    # same as dump but keys must be escaped. They may contain colon separated
                   6749:    # lists of values that may themself contain colons (e.g. symbs).
                   6750:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6751: }
                   6752: 
1.407     www      6753: # -------------------------------------------------------------- keys interface
                   6754: 
                   6755: sub getkeys {
                   6756:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6757:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6758:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6759:    my $uhome=&homeserver($uname,$udomain);
                   6760:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6761:    my @keyarray=();
1.800     albertel 6762:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6763:       next if ($key =~ /^error: 2 /);
1.800     albertel 6764:       push(@keyarray,&unescape($key));
1.407     www      6765:    }
                   6766:    return @keyarray;
1.318     matthew  6767: }
                   6768: 
1.319     matthew  6769: # --------------------------------------------------------------- currentdump
                   6770: sub currentdump {
1.328     matthew  6771:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6772:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6773:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6774:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6775:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6776:    my $rep;
                   6777: 
                   6778:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6779:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6780:                    $courseid)));
                   6781:    } else {
                   6782:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6783:    }
                   6784: 
1.318     matthew  6785:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6786:    #
1.318     matthew  6787:    my %returnhash=();
1.319     matthew  6788:    #
                   6789:    if ($rep eq "unknown_cmd") { 
                   6790:        # an old lond will not know currentdump
                   6791:        # Do a dump and make it look like a currentdump
1.822     albertel 6792:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6793:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6794:        my %hash = @tmp;
                   6795:        @tmp=();
1.424     matthew  6796:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6797:    } else {
                   6798:        my @pairs=split(/\&/,$rep);
1.800     albertel 6799:        foreach my $pair (@pairs) {
                   6800:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6801:            my ($symb,$param) = split(/:/,$key);
                   6802:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6803:                                                         &thaw_unescape($value);
1.319     matthew  6804:        }
1.191     harris41 6805:    }
1.12      www      6806:    return %returnhash;
1.424     matthew  6807: }
                   6808: 
                   6809: sub convert_dump_to_currentdump{
                   6810:     my %hash = %{shift()};
                   6811:     my %returnhash;
                   6812:     # Code ripped from lond, essentially.  The only difference
                   6813:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6814:     # we might run in to problems with parameter names =~ /^v\./
                   6815:     while (my ($key,$value) = each(%hash)) {
                   6816:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6817: 	$symb  = &unescape($symb);
                   6818: 	$param = &unescape($param);
1.424     matthew  6819:         next if ($v eq 'version' || $symb eq 'keys');
                   6820:         next if (exists($returnhash{$symb}) &&
                   6821:                  exists($returnhash{$symb}->{$param}) &&
                   6822:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6823:         $returnhash{$symb}->{$param}=$value;
                   6824:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6825:     }
                   6826:     #
                   6827:     # Remove all of the keys in the hashes which keep track of
                   6828:     # the version of the parameter.
                   6829:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6830:         # use a foreach because we are going to delete from the hash.
                   6831:         foreach my $key (keys(%$param_hash)) {
                   6832:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6833:         }
                   6834:     }
                   6835:     return \%returnhash;
1.12      www      6836: }
                   6837: 
1.627     albertel 6838: # ------------------------------------------------------ critical inc interface
                   6839: 
                   6840: sub cinc {
                   6841:     return &inc(@_,'critical');
                   6842: }
                   6843: 
1.449     matthew  6844: # --------------------------------------------------------------- inc interface
                   6845: 
                   6846: sub inc {
1.627     albertel 6847:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6848:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6849:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6850:     my $uhome=&homeserver($uname,$udomain);
                   6851:     my $items='';
                   6852:     if (! ref($store)) {
                   6853:         # got a single value, so use that instead
                   6854:         $items = &escape($store).'=&';
                   6855:     } elsif (ref($store) eq 'SCALAR') {
                   6856:         $items = &escape($$store).'=&';        
                   6857:     } elsif (ref($store) eq 'ARRAY') {
                   6858:         $items = join('=&',map {&escape($_);} @{$store});
                   6859:     } elsif (ref($store) eq 'HASH') {
                   6860:         while (my($key,$value) = each(%{$store})) {
                   6861:             $items.= &escape($key).'='.&escape($value).'&';
                   6862:         }
                   6863:     }
                   6864:     $items=~s/\&$//;
1.627     albertel 6865:     if ($critical) {
                   6866: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6867:     } else {
                   6868: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6869:     }
1.449     matthew  6870: }
                   6871: 
1.12      www      6872: # --------------------------------------------------------------- put interface
                   6873: 
                   6874: sub put {
1.134     albertel 6875:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6876:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6877:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6878:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6879:    my $items='';
1.800     albertel 6880:    foreach my $item (keys(%$storehash)) {
                   6881:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6882:    }
1.12      www      6883:    $items=~s/\&$//;
1.134     albertel 6884:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6885: }
                   6886: 
1.631     albertel 6887: # ------------------------------------------------------------ newput interface
                   6888: 
                   6889: sub newput {
                   6890:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6891:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6892:    if (!$uname) { $uname=$env{'user.name'}; }
                   6893:    my $uhome=&homeserver($uname,$udomain);
                   6894:    my $items='';
                   6895:    foreach my $key (keys(%$storehash)) {
                   6896:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6897:    }
                   6898:    $items=~s/\&$//;
                   6899:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6900: }
                   6901: 
                   6902: # ---------------------------------------------------------  putstore interface
                   6903: 
1.524     raeburn  6904: sub putstore {
1.1172.2.59  raeburn  6905:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6906:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6907:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6908:    my $uhome=&homeserver($uname,$udomain);
                   6909:    my $items='';
1.715     albertel 6910:    foreach my $key (keys(%$storehash)) {
                   6911:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6912:    }
1.715     albertel 6913:    $items=~s/\&$//;
1.716     albertel 6914:    my $esc_symb=&escape($symb);
                   6915:    my $esc_v=&escape($version);
1.715     albertel 6916:    my $reply =
1.716     albertel 6917:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6918: 	      $uhome);
1.1172.2.59  raeburn  6919:    if (($tolog) && ($reply eq 'ok')) {
                   6920:        my $namevalue='';
                   6921:        foreach my $key (keys(%{$storehash})) {
                   6922:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6923:        }
                   6924:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6925:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6926:                      '&version='.$esc_v.
                   6927:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6928:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6929:    }
1.715     albertel 6930:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6931:        # gfall back to way things use to be done
1.715     albertel 6932:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6933: 			    $uname);
1.524     raeburn  6934:    }
1.715     albertel 6935:    return $reply;
                   6936: }
                   6937: 
                   6938: sub old_putstore {
1.716     albertel 6939:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6940:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6941:     if (!$uname) { $uname=$env{'user.name'}; }
                   6942:     my $uhome=&homeserver($uname,$udomain);
                   6943:     my %newstorehash;
1.800     albertel 6944:     foreach my $item (keys(%$storehash)) {
                   6945: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6946: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6947:     }
                   6948:     my $items='';
                   6949:     my %allitems = ();
1.800     albertel 6950:     foreach my $item (keys(%newstorehash)) {
                   6951: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6952: 	    my $key = $1.':keys:'.$2;
                   6953: 	    $allitems{$key} .= $3.':';
                   6954: 	}
1.800     albertel 6955: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6956:     }
1.800     albertel 6957:     foreach my $item (keys(%allitems)) {
                   6958: 	$allitems{$item} =~ s/\:$//;
                   6959: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6960:     }
                   6961:     $items=~s/\&$//;
                   6962:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6963: }
                   6964: 
1.47      www      6965: # ------------------------------------------------------ critical put interface
                   6966: 
                   6967: sub cput {
1.134     albertel 6968:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6969:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6970:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6971:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6972:    my $items='';
1.800     albertel 6973:    foreach my $item (keys(%$storehash)) {
                   6974:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6975:    }
1.47      www      6976:    $items=~s/\&$//;
1.134     albertel 6977:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6978: }
                   6979: 
                   6980: # -------------------------------------------------------------- eget interface
                   6981: 
                   6982: sub eget {
1.133     albertel 6983:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6984:    my $items='';
1.800     albertel 6985:    foreach my $item (@$storearr) {
                   6986:        $items.=&escape($item).'&';
1.191     harris41 6987:    }
1.12      www      6988:    $items=~s/\&$//;
1.620     albertel 6989:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6990:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6991:    my $uhome=&homeserver($uname,$udomain);
                   6992:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6993:    my @pairs=split(/\&/,$rep);
                   6994:    my %returnhash=();
1.42      www      6995:    my $i=0;
1.800     albertel 6996:    foreach my $item (@$storearr) {
                   6997:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6998:       $i++;
1.191     harris41 6999:    }
1.12      www      7000:    return %returnhash;
                   7001: }
                   7002: 
1.667     albertel 7003: # ------------------------------------------------------------ tmpput interface
                   7004: sub tmpput {
1.802     raeburn  7005:     my ($storehash,$server,$context)=@_;
1.667     albertel 7006:     my $items='';
1.800     albertel 7007:     foreach my $item (keys(%$storehash)) {
                   7008: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7009:     }
                   7010:     $items=~s/\&$//;
1.802     raeburn  7011:     if (defined($context)) {
                   7012:         $items .= ':'.&escape($context);
                   7013:     }
1.667     albertel 7014:     return &reply("tmpput:$items",$server);
                   7015: }
                   7016: 
                   7017: # ------------------------------------------------------------ tmpget interface
                   7018: sub tmpget {
1.688     albertel 7019:     my ($token,$server)=@_;
                   7020:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7021:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7022:     my %returnhash;
1.1172.2.85  raeburn  7023:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7024:         return %returnhash;
                   7025:     }
1.667     albertel 7026:     foreach my $item (split(/\&/,$rep)) {
                   7027: 	my ($key,$value)=split(/=/,$item);
                   7028: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7029:     }
                   7030:     return %returnhash;
                   7031: }
                   7032: 
1.1113    raeburn  7033: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7034: sub tmpdel {
                   7035:     my ($token,$server)=@_;
                   7036:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7037:     return &reply("tmpdel:$token",$server);
                   7038: }
                   7039: 
1.1172.2.13  raeburn  7040: # ------------------------------------------------------------ get_timebased_id
                   7041: 
                   7042: sub get_timebased_id {
                   7043:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7044:         $maxtries) = @_;
                   7045:     my ($newid,$error,$dellock);
                   7046:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7047:         return ('','ok','invalid call to get suffix');
                   7048:     }
                   7049: 
                   7050: # set defaults for any optional args for which values were not supplied
                   7051:     if ($who eq '') {
                   7052:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7053:     }
                   7054:     if (!$locktries) {
                   7055:         $locktries = 3;
                   7056:     }
                   7057:     if (!$maxtries) {
                   7058:         $maxtries = 10;
                   7059:     }
                   7060: 
                   7061:     if (($cdom eq '') || ($cnum eq '')) {
                   7062:         if ($env{'request.course.id'}) {
                   7063:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7064:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7065:         }
                   7066:         if (($cdom eq '') || ($cnum eq '')) {
                   7067:             return ('','ok','call to get suffix not in course context');
                   7068:         }
                   7069:     }
                   7070: 
                   7071: # construct locking item
                   7072:     my $lockhash = {
                   7073:                       $prefix."\0".'locked_'.$keyid => $who,
                   7074:                    };
                   7075:     my $tries = 0;
                   7076: 
                   7077: # attempt to get lock on nohist_$namespace file
                   7078:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7079:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7080:         $tries ++;
                   7081:         sleep 1;
                   7082:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7083:     }
                   7084: 
                   7085: # attempt to get unique identifier, based on current timestamp
                   7086:     if ($gotlock eq 'ok') {
                   7087:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7088:         my $id = time;
                   7089:         $newid = $id;
1.1172.2.56  raeburn  7090:         if ($idtype eq 'addcode') {
                   7091:             $newid .= &sixnum_code();
                   7092:         }
1.1172.2.13  raeburn  7093:         my $idtries = 0;
                   7094:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7095:             if ($idtype eq 'concat') {
                   7096:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7097:             } elsif ($idtype eq 'addcode') {
                   7098:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7099:             } else {
                   7100:                 $newid ++;
                   7101:             }
                   7102:             $idtries ++;
                   7103:         }
                   7104:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7105:             my %new_item =  (
                   7106:                               $prefix."\0".$newid => $who,
                   7107:                             );
                   7108:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7109:                                                  $cdom,$cnum);
                   7110:             if ($putresult ne 'ok') {
                   7111:                 undef($newid);
                   7112:                 $error = 'error saving new item: '.$putresult;
                   7113:             }
                   7114:         } else {
1.1172.2.56  raeburn  7115:              undef($newid);
1.1172.2.13  raeburn  7116:              $error = ('error: no unique suffix available for the new item ');
                   7117:         }
                   7118: #  remove lock
                   7119:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7120:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7121:     } else {
                   7122:         $error = "error: could not obtain lockfile\n";
                   7123:         $dellock = 'ok';
1.1172.2.58  raeburn  7124:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7125:             $dellock = 'nolock';
                   7126:         }
1.1172.2.13  raeburn  7127:     }
                   7128:     return ($newid,$dellock,$error);
                   7129: }
                   7130: 
1.1172.2.56  raeburn  7131: sub sixnum_code {
                   7132:     my $code;
                   7133:     for (0..6) {
                   7134:         $code .= int( rand(9) );
                   7135:     }
                   7136:     return $code;
                   7137: }
                   7138: 
1.765     albertel 7139: # -------------------------------------------------- portfolio access checking
                   7140: 
                   7141: sub portfolio_access {
1.1172.2.77  raeburn  7142:     my ($requrl,$clientip) = @_;
1.765     albertel 7143:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7144:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7145:     if ($result) {
                   7146:         my %setters;
                   7147:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7148:             my ($startblock,$endblock) =
                   7149:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7150:             if ($startblock && $endblock) {
                   7151:                 return 'B';
                   7152:             }
                   7153:         } else {
                   7154:             my ($startblock,$endblock) =
                   7155:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7156:             if ($startblock && $endblock) {
                   7157:                 return 'B';
                   7158:             }
                   7159:         }
                   7160:     }
1.765     albertel 7161:     if ($result eq 'ok') {
1.766     albertel 7162:        return 'F';
1.765     albertel 7163:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7164:        return 'A';
1.765     albertel 7165:     }
1.766     albertel 7166:     return '';
1.765     albertel 7167: }
                   7168: 
                   7169: sub get_portfolio_access {
1.1172.2.77  raeburn  7170:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7171: 
                   7172:     if (!ref($access_hash)) {
                   7173: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7174: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7175: 						   $file_name);
                   7176: 	$access_hash = $access_controls{$file_name};
                   7177:     }
                   7178: 
1.1172.2.77  raeburn  7179:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7180:     my $now = time;
                   7181:     if (ref($access_hash) eq 'HASH') {
                   7182:         foreach my $key (keys(%{$access_hash})) {
                   7183:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7184:             if ($start > $now) {
                   7185:                 next;
                   7186:             }
                   7187:             if ($end && $end<$now) {
                   7188:                 next;
                   7189:             }
                   7190:             if ($scope eq 'public') {
                   7191:                 $public = $key;
                   7192:                 last;
                   7193:             } elsif ($scope eq 'guest') {
                   7194:                 $guest = $key;
                   7195:             } elsif ($scope eq 'domains') {
                   7196:                 push(@domains,$key);
                   7197:             } elsif ($scope eq 'users') {
                   7198:                 push(@users,$key);
                   7199:             } elsif ($scope eq 'course') {
                   7200:                 push(@courses,$key);
                   7201:             } elsif ($scope eq 'group') {
                   7202:                 push(@groups,$key);
1.1172.2.77  raeburn  7203:             } elsif ($scope eq 'ip') {
                   7204:                 push(@ips,$key);
1.765     albertel 7205:             }
                   7206:         }
                   7207:         if ($public) {
                   7208:             return 'ok';
1.1172.2.77  raeburn  7209:         } elsif (@ips > 0) {
                   7210:             my $allowed;
                   7211:             foreach my $ipkey (@ips) {
                   7212:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7213:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7214:                         $allowed = 1;
                   7215:                         last;
                   7216:                     }
                   7217:                 }
                   7218:             }
                   7219:             if ($allowed) {
                   7220:                 return 'ok';
                   7221:             }
1.765     albertel 7222:         }
                   7223:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7224:             if ($guest) {
                   7225:                 return $guest;
                   7226:             }
                   7227:         } else {
                   7228:             if (@domains > 0) {
                   7229:                 foreach my $domkey (@domains) {
                   7230:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7231:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7232:                             return 'ok';
                   7233:                         }
                   7234:                     }
                   7235:                 }
                   7236:             }
                   7237:             if (@users > 0) {
                   7238:                 foreach my $userkey (@users) {
1.865     raeburn  7239:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7240:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7241:                             if (ref($item) eq 'HASH') {
                   7242:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7243:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7244:                                     return 'ok';
                   7245:                                 }
                   7246:                             }
                   7247:                         }
                   7248:                     } 
1.765     albertel 7249:                 }
                   7250:             }
                   7251:             my %roleshash;
                   7252:             my @courses_and_groups = @courses;
                   7253:             push(@courses_and_groups,@groups); 
                   7254:             if (@courses_and_groups > 0) {
                   7255:                 my (%allgroups,%allroles); 
                   7256:                 my ($start,$end,$role,$sec,$group);
                   7257:                 foreach my $envkey (%env) {
1.1060    raeburn  7258:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7259:                         my $cid = $2.'_'.$3; 
                   7260:                         if ($1 eq 'gr') {
                   7261:                             $group = $4;
                   7262:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7263:                         } else {
                   7264:                             if ($4 eq '') {
                   7265:                                 $sec = 'none';
                   7266:                             } else {
                   7267:                                 $sec = $4;
                   7268:                             }
                   7269:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7270:                         }
1.811     albertel 7271:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7272:                         my $cid = $2.'_'.$3;
                   7273:                         if ($4 eq '') {
                   7274:                             $sec = 'none';
                   7275:                         } else {
                   7276:                             $sec = $4;
                   7277:                         }
                   7278:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7279:                     }
                   7280:                 }
                   7281:                 if (keys(%allroles) == 0) {
                   7282:                     return;
                   7283:                 }
                   7284:                 foreach my $key (@courses_and_groups) {
                   7285:                     my %content = %{$$access_hash{$key}};
                   7286:                     my $cnum = $content{'number'};
                   7287:                     my $cdom = $content{'domain'};
                   7288:                     my $cid = $cdom.'_'.$cnum;
                   7289:                     if (!exists($allroles{$cid})) {
                   7290:                         next;
                   7291:                     }    
                   7292:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7293:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7294:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7295:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7296:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7297:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7298:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7299:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7300:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7301:                                         if (grep/^all$/,@sections) {
                   7302:                                             return 'ok';
                   7303:                                         } else {
                   7304:                                             if (grep/^$sec$/,@sections) {
                   7305:                                                 return 'ok';
                   7306:                                             }
                   7307:                                         }
                   7308:                                     }
                   7309:                                 }
                   7310:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7311:                                     if (grep/^none$/,@groups) {
                   7312:                                         return 'ok';
                   7313:                                     }
                   7314:                                 } else {
                   7315:                                     if (grep/^all$/,@groups) {
                   7316:                                         return 'ok';
                   7317:                                     } 
                   7318:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7319:                                         if (grep/^$group$/,@groups) {
                   7320:                                             return 'ok';
                   7321:                                         }
                   7322:                                     }
                   7323:                                 } 
                   7324:                             }
                   7325:                         }
                   7326:                     }
                   7327:                 }
                   7328:             }
                   7329:             if ($guest) {
                   7330:                 return $guest;
                   7331:             }
                   7332:         }
                   7333:     }
                   7334:     return;
                   7335: }
                   7336: 
                   7337: sub course_group_datechecker {
                   7338:     my ($dates,$now,$status) = @_;
                   7339:     my ($start,$end) = split(/\./,$dates);
                   7340:     if (!$start && !$end) {
                   7341:         return 'ok';
                   7342:     }
                   7343:     if (grep/^active$/,@{$status}) {
                   7344:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7345:             return 'ok';
                   7346:         }
                   7347:     }
                   7348:     if (grep/^previous$/,@{$status}) {
                   7349:         if ($end > $now ) {
                   7350:             return 'ok';
                   7351:         }
                   7352:     }
                   7353:     if (grep/^future$/,@{$status}) {
                   7354:         if ($start > $now) {
                   7355:             return 'ok';
                   7356:         }
                   7357:     }
                   7358:     return; 
                   7359: }
                   7360: 
                   7361: sub parse_portfolio_url {
                   7362:     my ($url) = @_;
                   7363: 
                   7364:     my ($type,$udom,$unum,$group,$file_name);
                   7365:     
1.823     albertel 7366:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7367: 	$type = 1;
                   7368:         $udom = $1;
                   7369:         $unum = $2;
                   7370:         $file_name = $3;
1.823     albertel 7371:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7372: 	$type = 2;
                   7373:         $udom = $1;
                   7374:         $unum = $2;
                   7375:         $group = $3;
                   7376:         $file_name = $3.'/'.$4;
                   7377:     }
                   7378:     if (wantarray) {
                   7379: 	return ($type,$udom,$unum,$file_name,$group);
                   7380:     }
                   7381:     return $type;
                   7382: }
                   7383: 
                   7384: sub is_portfolio_url {
                   7385:     my ($url) = @_;
                   7386:     return scalar(&parse_portfolio_url($url));
                   7387: }
                   7388: 
1.798     raeburn  7389: sub is_portfolio_file {
                   7390:     my ($file) = @_;
1.820     raeburn  7391:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7392:         return 1;
                   7393:     }
                   7394:     return;
                   7395: }
                   7396: 
1.976     raeburn  7397: sub usertools_access {
1.1084    raeburn  7398:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7399:     my ($access,%tools);
                   7400:     if ($context eq '') {
                   7401:         $context = 'tools';
                   7402:     }
                   7403:     if ($context eq 'requestcourses') {
                   7404:         %tools = (
                   7405:                       official   => 1,
                   7406:                       unofficial => 1,
1.1006    raeburn  7407:                       community  => 1,
1.1172.2.37  raeburn  7408:                       textbook   => 1,
1.985     raeburn  7409:                  );
1.1172.2.9  raeburn  7410:     } elsif ($context eq 'requestauthor') {
                   7411:         %tools = (
                   7412:                       requestauthor => 1,
                   7413:                  );
1.985     raeburn  7414:     } else {
                   7415:         %tools = (
                   7416:                       aboutme   => 1,
                   7417:                       blog      => 1,
1.1172.2.6  raeburn  7418:                       webdav    => 1,
1.985     raeburn  7419:                       portfolio => 1,
                   7420:                  );
                   7421:     }
1.976     raeburn  7422:     return if (!defined($tools{$tool}));
                   7423: 
1.1172.2.35  raeburn  7424:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7425:         $udom = $env{'user.domain'};
                   7426:         $uname = $env{'user.name'};
                   7427:     }
                   7428: 
1.978     raeburn  7429:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7430:         if ($action ne 'reload') {
1.985     raeburn  7431:             if ($context eq 'requestcourses') {
                   7432:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7433:             } elsif ($context eq 'requestauthor') {
                   7434:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7435:             } else {
                   7436:                 return $env{'environment.availabletools.'.$tool};
                   7437:             }
                   7438:         }
1.976     raeburn  7439:     }
                   7440: 
1.1172.2.9  raeburn  7441:     my ($toolstatus,$inststatus,$envkey);
                   7442:     if ($context eq 'requestauthor') {
                   7443:         $envkey = $context;
                   7444:     } else {
                   7445:         $envkey = $context.'.'.$tool;
                   7446:     }
1.976     raeburn  7447: 
1.985     raeburn  7448:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7449:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7450:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7451:         $inststatus = $env{'environment.inststatus'};
                   7452:     } else {
1.1084    raeburn  7453:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7454:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7455:             $inststatus = $userenvref->{'inststatus'};
                   7456:         } else {
1.1172.2.9  raeburn  7457:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7458:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7459:             $inststatus = $userenv{'inststatus'};
                   7460:         }
1.976     raeburn  7461:     }
                   7462: 
                   7463:     if ($toolstatus ne '') {
                   7464:         if ($toolstatus) {
                   7465:             $access = 1;
                   7466:         } else {
                   7467:             $access = 0;
                   7468:         }
                   7469:         return $access;
                   7470:     }
                   7471: 
1.1084    raeburn  7472:     my ($is_adv,%domdef);
                   7473:     if (ref($is_advref) eq 'HASH') {
                   7474:         $is_adv = $is_advref->{'is_adv'};
                   7475:     } else {
                   7476:         $is_adv = &is_advanced_user($udom,$uname);
                   7477:     }
                   7478:     if (ref($domdefref) eq 'HASH') {
                   7479:         %domdef = %{$domdefref};
                   7480:     } else {
                   7481:         %domdef = &get_domain_defaults($udom);
                   7482:     }
1.976     raeburn  7483:     if (ref($domdef{$tool}) eq 'HASH') {
                   7484:         if ($is_adv) {
                   7485:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7486:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7487:                     $access = 1;
                   7488:                 } else {
                   7489:                     $access = 0;
                   7490:                 }
                   7491:                 return $access;
                   7492:             }
                   7493:         }
                   7494:         if ($inststatus ne '') {
                   7495:             my ($hasaccess,$hasnoaccess);
                   7496:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7497:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7498:                     if ($domdef{$tool}{$affiliation}) {
                   7499:                         $hasaccess = 1;
                   7500:                     } else {
                   7501:                         $hasnoaccess = 1;
                   7502:                     }
                   7503:                 }
                   7504:             }
                   7505:             if ($hasaccess || $hasnoaccess) {
                   7506:                 if ($hasaccess) {
                   7507:                     $access = 1;
                   7508:                 } elsif ($hasnoaccess) {
                   7509:                     $access = 0; 
                   7510:                 }
                   7511:                 return $access;
                   7512:             }
                   7513:         } else {
                   7514:             if ($domdef{$tool}{'default'} ne '') {
                   7515:                 if ($domdef{$tool}{'default'}) {
                   7516:                     $access = 1;
                   7517:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7518:                     $access = 0;
                   7519:                 }
                   7520:                 return $access;
                   7521:             }
                   7522:         }
                   7523:     } else {
1.1172.2.6  raeburn  7524:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7525:             $access = 1;
                   7526:         } else {
                   7527:             $access = 0;
                   7528:         }
1.976     raeburn  7529:         return $access;
                   7530:     }
                   7531: }
                   7532: 
1.1050    raeburn  7533: sub is_course_owner {
                   7534:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7535:     if (($udom eq '') || ($uname eq '')) {
                   7536:         $udom = $env{'user.domain'};
                   7537:         $uname = $env{'user.name'};
                   7538:     }
                   7539:     unless (($udom eq '') || ($uname eq '')) {
                   7540:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7541:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7542:                 return 1;
                   7543:             } else {
                   7544:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7545:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7546:                     return 1;
                   7547:                 }
                   7548:             }
                   7549:         }
                   7550:     }
                   7551:     return;
                   7552: }
                   7553: 
1.976     raeburn  7554: sub is_advanced_user {
                   7555:     my ($udom,$uname) = @_;
1.1085    raeburn  7556:     if ($udom ne '' && $uname ne '') {
                   7557:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7558:             if (wantarray) {
                   7559:                 return ($env{'user.adv'},$env{'user.author'});
                   7560:             } else {
                   7561:                 return $env{'user.adv'};
                   7562:             }
1.1085    raeburn  7563:         }
                   7564:     }
1.976     raeburn  7565:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7566:     my %allroles;
1.1128    raeburn  7567:     my ($is_adv,$is_author);
1.976     raeburn  7568:     foreach my $role (keys(%roleshash)) {
                   7569:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7570:         my $area = '/'.$tdomain.'/'.$trest;
                   7571:         if ($sec ne '') {
                   7572:             $area .= '/'.$sec;
                   7573:         }
                   7574:         if (($area ne '') && ($trole ne '')) {
                   7575:             my $spec=$trole.'.'.$area;
                   7576:             if ($trole =~ /^cr\//) {
                   7577:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7578:             } elsif ($trole ne 'gr') {
                   7579:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7580:             }
1.1128    raeburn  7581:             if ($trole eq 'au') {
                   7582:                 $is_author = 1;
                   7583:             }
1.976     raeburn  7584:         }
                   7585:     }
                   7586:     foreach my $role (keys(%allroles)) {
                   7587:         last if ($is_adv);
                   7588:         foreach my $item (split(/:/,$allroles{$role})) {
                   7589:             if ($item ne '') {
                   7590:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7591:                 if ($privilege eq 'adv') {
                   7592:                     $is_adv = 1;
                   7593:                     last;
                   7594:                 }
                   7595:             }
                   7596:         }
                   7597:     }
1.1128    raeburn  7598:     if (wantarray) {
                   7599:         return ($is_adv,$is_author);
                   7600:     }
1.976     raeburn  7601:     return $is_adv;
                   7602: }
1.798     raeburn  7603: 
1.1035    raeburn  7604: sub check_can_request {
1.1036    raeburn  7605:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7606:     my $canreq = 0;
                   7607:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7608:     my @options = ('approval','validate','autolimit');
                   7609:     my $optregex = join('|',@options);
                   7610:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7611:         foreach my $type (@{$types}) {
                   7612:             if (&usertools_access($env{'user.name'},
                   7613:                                   $env{'user.domain'},
                   7614:                                   $type,undef,'requestcourses')) {
                   7615:                 $canreq ++;
1.1036    raeburn  7616:                 if (ref($request_domains) eq 'HASH') {
                   7617:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7618:                 }
1.1035    raeburn  7619:                 if ($dom eq $env{'user.domain'}) {
                   7620:                     $can_request->{$type} = 1;
                   7621:                 }
                   7622:             }
                   7623:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7624:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7625:                 if (@curr > 0) {
1.1036    raeburn  7626:                     foreach my $item (@curr) {
                   7627:                         if (ref($request_domains) eq 'HASH') {
                   7628:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7629:                             if ($otherdom ne '') {
                   7630:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7631:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7632:                                         push(@{$request_domains->{$type}},$otherdom);
                   7633:                                     }
                   7634:                                 } else {
                   7635:                                     push(@{$request_domains->{$type}},$otherdom);
                   7636:                                 }
                   7637:                             }
                   7638:                         }
                   7639:                     }
                   7640:                     unless($dom eq $env{'user.domain'}) {
                   7641:                         $canreq ++;
1.1035    raeburn  7642:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7643:                             $can_request->{$type} = 1;
                   7644:                         }
                   7645:                     }
                   7646:                 }
                   7647:             }
                   7648:         }
                   7649:     }
                   7650:     return $canreq;
                   7651: }
                   7652: 
1.341     www      7653: # ---------------------------------------------- Custom access rule evaluation
                   7654: 
                   7655: sub customaccess {
                   7656:     my ($priv,$uri)=@_;
1.807     albertel 7657:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7658:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7659:     $udom = &LONCAPA::clean_domain($udom);
                   7660:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7661:     my $access=0;
1.800     albertel 7662:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7663: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7664: 	if ($type eq 'user') {
                   7665: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7666: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7667: 		if ($tdom) {
                   7668: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7669: 		}
1.896     albertel 7670: 		if ($tuname) {
                   7671: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7672: 		}
                   7673: 		$access=($effect eq 'allow');
                   7674: 		last;
                   7675: 	    }
                   7676: 	} else {
                   7677: 	    if ($role) {
                   7678: 		if ($role ne $urole) { next; }
                   7679: 	    }
                   7680: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7681: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7682: 		if ($tdom) {
                   7683: 		    if ($tdom ne $udom) { next; }
                   7684: 		}
                   7685: 		if ($tcrs) {
                   7686: 		    if ($tcrs ne $ucrs) { next; }
                   7687: 		}
                   7688: 		if ($tsec) {
                   7689: 		    if ($tsec ne $usec) { next; }
                   7690: 		}
                   7691: 		$access=($effect eq 'allow');
                   7692: 		last;
                   7693: 	    }
                   7694: 	    if ($realm eq '' && $role eq '') {
                   7695: 		$access=($effect eq 'allow');
                   7696: 	    }
1.402     bowersj2 7697: 	}
1.341     www      7698:     }
                   7699:     return $access;
                   7700: }
                   7701: 
1.103     harris41 7702: # ------------------------------------------------- Check for a user privilege
1.12      www      7703: 
                   7704: sub allowed {
1.1172.2.65  raeburn  7705:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7706:     my $ver_orguri=$uri;
1.439     www      7707:     $uri=&deversion($uri);
1.152     www      7708:     my $orguri=$uri;
1.52      www      7709:     $uri=&declutter($uri);
1.809     raeburn  7710: 
1.810     raeburn  7711:     if ($priv eq 'evb') {
                   7712: # Evade communication block restrictions for specified role in a course
                   7713:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7714:             return $1;
                   7715:         } else {
                   7716:             return;
                   7717:         }
                   7718:     }
                   7719: 
1.620     albertel 7720:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7721: # Free bre access to adm and meta resources
1.775     albertel 7722:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7723: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7724: 	&& ($priv eq 'bre')) {
1.14      www      7725: 	return 'F';
1.159     www      7726:     }
                   7727: 
1.545     banghart 7728: # Free bre access to user's own portfolio contents
1.714     raeburn  7729:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7730:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7731: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7732:         my %setters;
                   7733:         my ($startblock,$endblock) = 
                   7734:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7735:         if ($startblock && $endblock) {
                   7736:             return 'B';
                   7737:         } else {
                   7738:             return 'F';
                   7739:         }
1.545     banghart 7740:     }
                   7741: 
1.762     raeburn  7742: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7743:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7744:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7745:         if (exists($env{'request.course.id'})) {
                   7746:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7747:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7748:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7749:                 my $courseprivid=$env{'request.course.id'};
                   7750:                 $courseprivid=~s/\_/\//;
                   7751:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7752:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7753:                     return $1; 
1.762     raeburn  7754:                 } else {
                   7755:                     if ($env{'request.course.sec'}) {
                   7756:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7757:                     }
                   7758:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7759:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7760:                         return $2;
                   7761:                     }
1.714     raeburn  7762:                 }
                   7763:             }
                   7764:         }
                   7765:     }
                   7766: 
1.159     www      7767: # Free bre to public access
                   7768: 
                   7769:     if ($priv eq 'bre') {
1.238     www      7770:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7771: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7772:            return 'F'; 
                   7773:         }
1.238     www      7774:         if ($copyright eq 'priv') {
                   7775:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7776: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7777: 		return '';
                   7778:             }
                   7779:         }
                   7780:         if ($copyright eq 'domain') {
                   7781:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7782: 	    unless (($env{'user.domain'} eq $1) ||
                   7783:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7784: 		return '';
                   7785:             }
1.262     matthew  7786:         }
1.620     albertel 7787:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7788:             # Library role, so allow browsing of resources in this domain.
                   7789:             return 'F';
1.238     www      7790:         }
1.341     www      7791:         if ($copyright eq 'custom') {
                   7792: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7793:         }
1.14      www      7794:     }
1.264     matthew  7795:     # Domain coordinator is trying to create a course
1.620     albertel 7796:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7797:         # uri is the requested domain in this case.
                   7798:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7799:         # a role of dc for the domain in question.
1.620     albertel 7800:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7801:     }
1.29      www      7802: 
1.52      www      7803:     my $thisallowed='';
                   7804:     my $statecond=0;
                   7805:     my $courseprivid='';
                   7806: 
1.1039    raeburn  7807:     my $ownaccess;
1.1043    raeburn  7808:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7809:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7810:         if ($uri eq '') {
                   7811:             $ownaccess = 1;
                   7812:         } else {
                   7813:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7814:                 my $udom = $env{'user.domain'};
                   7815:                 my $uname = $env{'user.name'};
                   7816:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7817:                     $ownaccess = 1;
1.1040    raeburn  7818:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7819:                     unless ($uri =~ m{\.\./}) {
                   7820:                         $ownaccess = 1;
                   7821:                     }
                   7822:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7823:                     my $now = time;
                   7824:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7825:                         my $adom = $1;
                   7826:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7827:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7828:                                 my ($start,$end) = split('.',$env{$key});
                   7829:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7830:                                     $ownaccess = 1;
                   7831:                                     last;
                   7832:                                 }
                   7833:                             }
                   7834:                         }
                   7835:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7836:                         my $adom = $1;
                   7837:                         my $aname = $2;
1.1042    raeburn  7838:                         foreach my $role ('ca','aa') { 
                   7839:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7840:                                 my ($start,$end) =
                   7841:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7842:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7843:                                     $ownaccess = 1;
                   7844:                                     last;
                   7845:                                 }
1.1039    raeburn  7846:                             }
                   7847:                         }
                   7848:                     }
                   7849:                 }
                   7850:             }
                   7851:         }
                   7852:     }
                   7853: 
1.52      www      7854: # Course
                   7855: 
1.620     albertel 7856:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7857:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7858:             $thisallowed.=$1;
                   7859:         }
1.52      www      7860:     }
1.29      www      7861: 
1.52      www      7862: # Domain
                   7863: 
1.620     albertel 7864:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7865:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7866:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7867:             $thisallowed.=$1;
                   7868:         }
1.12      www      7869:     }
1.52      www      7870: 
1.1141    raeburn  7871: # User who is not author or co-author might still be able to edit
                   7872: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7873:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7874:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7875:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7876:             $thisallowed.=$1;
                   7877:         }
                   7878:     }
                   7879: 
1.52      www      7880: # Course: uri itself is a course
1.66      www      7881:     my $courseuri=$uri;
                   7882:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7883:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7884: 
1.620     albertel 7885:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7886:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7887:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7888:             $thisallowed.=$1;
                   7889:         }
1.12      www      7890:     }
1.29      www      7891: 
1.665     albertel 7892: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7893: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7894:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7895: 	$thisallowed='';
1.671     raeburn  7896:         my ($match)=&is_on_map($uri);
                   7897:         if ($match) {
                   7898:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7899:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7900:                 my $value = $1;
                   7901:                 if ($noblockcheck) {
                   7902:                     $thisallowed.=$value;
1.1162    raeburn  7903:                 } else {
1.1172.2.65  raeburn  7904:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7905:                     if (@blockers > 0) {
                   7906:                         $thisallowed = 'B';
                   7907:                     } else {
                   7908:                         $thisallowed.=$value;
                   7909:                     }
1.1162    raeburn  7910:                 }
1.671     raeburn  7911:             }
                   7912:         } else {
1.705     albertel 7913:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7914:             if ($refuri) {
                   7915:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7916:                     $thisallowed='F';
1.671     raeburn  7917:                 } else {
                   7918:                     $refuri=&declutter($refuri);
                   7919:                     my ($match) = &is_on_map($refuri);
                   7920:                     if ($match) {
1.1172.2.65  raeburn  7921:                         if ($noblockcheck) {
1.1162    raeburn  7922:                             $thisallowed='F';
1.1172.2.65  raeburn  7923:                         } else {
                   7924:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7925:                             if (@blockers > 0) {
                   7926:                                 $thisallowed = 'B';
                   7927:                             } else {
                   7928:                                 $thisallowed='F';
                   7929:                             }
1.1162    raeburn  7930:                         }
1.671     raeburn  7931:                     }
1.669     raeburn  7932:                 }
1.671     raeburn  7933:             }
                   7934:         }
1.314     www      7935:     }
1.492     albertel 7936: 
1.766     albertel 7937:     if ($priv eq 'bre'
                   7938: 	&& $thisallowed ne 'F' 
                   7939: 	&& $thisallowed ne '2'
                   7940: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7941: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7942:     }
                   7943:     
1.52      www      7944: # Full access at system, domain or course-wide level? Exit.
1.29      www      7945:     if ($thisallowed=~/F/) {
                   7946: 	return 'F';
                   7947:     }
                   7948: 
1.52      www      7949: # If this is generating or modifying users, exit with special codes
1.29      www      7950: 
1.643     www      7951:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7952: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7953: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7954: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7955: 	    unless ($auname) { return $thisallowed; }
                   7956: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7957: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7958: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7959: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7960: 	}
1.52      www      7961: 	return $thisallowed;
                   7962:     }
                   7963: #
1.103     harris41 7964: # Gathered so far: system, domain and course wide privileges
1.52      www      7965: #
                   7966: # Course: See if uri or referer is an individual resource that is part of 
                   7967: # the course
                   7968: 
1.620     albertel 7969:     if ($env{'request.course.id'}) {
1.232     www      7970: 
1.620     albertel 7971:        $courseprivid=$env{'request.course.id'};
                   7972:        if ($env{'request.course.sec'}) {
                   7973:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7974:        }
                   7975:        $courseprivid=~s/\_/\//;
                   7976:        my $checkreferer=1;
1.232     www      7977:        my ($match,$cond)=&is_on_map($uri);
                   7978:        if ($match) {
                   7979:            $statecond=$cond;
1.620     albertel 7980:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7981:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7982:                my $value = $1;
                   7983:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7984:                    if ($noblockcheck) {
1.1162    raeburn  7985:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7986:                    } else {
                   7987:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7988:                        if (@blockers > 0) {
                   7989:                            $thisallowed = 'B';
                   7990:                        } else {
                   7991:                            $thisallowed.=$value;
                   7992:                        }
1.1162    raeburn  7993:                    }
                   7994:                } else {
                   7995:                    $thisallowed.=$value;
                   7996:                }
1.52      www      7997:                $checkreferer=0;
                   7998:            }
1.29      www      7999:        }
1.83      www      8000:        
1.148     www      8001:        if ($checkreferer) {
1.620     albertel 8002: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8003:             unless ($refuri) {
1.800     albertel 8004:                 foreach my $key (keys(%env)) {
                   8005: 		    if ($key=~/^httpref\..*\*/) {
                   8006: 			my $pattern=$key;
1.156     www      8007:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8008:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8009:                         $pattern=~s/\//\\\//g;
1.152     www      8010:                         if ($orguri=~/$pattern/) {
1.800     albertel 8011: 			    $refuri=$env{$key};
1.148     www      8012:                         }
                   8013:                     }
1.191     harris41 8014:                 }
1.148     www      8015:             }
1.232     www      8016: 
1.148     www      8017:          if ($refuri) { 
1.152     www      8018: 	  $refuri=&declutter($refuri);
1.232     www      8019:           my ($match,$cond)=&is_on_map($refuri);
                   8020:             if ($match) {
                   8021:               my $refstatecond=$cond;
1.620     albertel 8022:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8023:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8024:                   my $value = $1;
                   8025:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8026:                       if ($noblockcheck) {
1.1162    raeburn  8027:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8028:                       } else {
                   8029:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8030:                           if (@blockers > 0) {
                   8031:                               $thisallowed = 'B';
                   8032:                           } else {
                   8033:                               $thisallowed.=$value;
                   8034:                           }
1.1162    raeburn  8035:                       }
                   8036:                   } else {
                   8037:                       $thisallowed.=$value;
                   8038:                   }
1.53      www      8039:                   $uri=$refuri;
                   8040:                   $statecond=$refstatecond;
1.52      www      8041:               }
                   8042:           }
1.148     www      8043:         }
1.29      www      8044:        }
1.52      www      8045:    }
1.29      www      8046: 
1.52      www      8047: #
1.103     harris41 8048: # Gathered now: all privileges that could apply, and condition number
1.52      www      8049: # 
                   8050: #
                   8051: # Full or no access?
                   8052: #
1.29      www      8053: 
1.52      www      8054:     if ($thisallowed=~/F/) {
                   8055: 	return 'F';
                   8056:     }
1.29      www      8057: 
1.52      www      8058:     unless ($thisallowed) {
                   8059:         return '';
                   8060:     }
1.29      www      8061: 
1.52      www      8062: # Restrictions exist, deal with them
                   8063: #
                   8064: #   C:according to course preferences
                   8065: #   R:according to resource settings
                   8066: #   L:unless locked
                   8067: #   X:according to user session state
                   8068: #
                   8069: 
                   8070: # Possibly locked functionality, check all courses
1.54      www      8071: # Locks might take effect only after 10 minutes cache expiration for other
                   8072: # courses, and 2 minutes for current course
1.52      www      8073: 
                   8074:     my $envkey;
                   8075:     if ($thisallowed=~/L/) {
1.1000    raeburn  8076:         foreach $envkey (keys(%env)) {
1.54      www      8077:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8078:                my $courseid=$2;
                   8079:                my $roleid=$1.'.'.$2;
1.92      www      8080:                $courseid=~s/^\///;
1.54      www      8081:                my $expiretime=600;
1.620     albertel 8082:                if ($env{'request.role'} eq $roleid) {
1.54      www      8083: 		  $expiretime=120;
                   8084:                }
                   8085: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8086:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8087:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8088: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8089:                }
1.620     albertel 8090:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8091:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8092: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8093:                        &log($env{'user.domain'},$env{'user.name'},
                   8094:                             $env{'user.home'},
1.57      www      8095:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8096:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8097:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8098: 		       return '';
                   8099:                    }
                   8100:                }
1.620     albertel 8101:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8102:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8103: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8104:                        &log($env{'user.domain'},$env{'user.name'},
                   8105:                             $env{'user.home'},
1.57      www      8106:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8107:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8108:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8109: 		       return '';
                   8110:                    }
                   8111:                }
                   8112: 	   }
1.29      www      8113:        }
1.52      www      8114:     }
                   8115:    
                   8116: #
                   8117: # Rest of the restrictions depend on selected course
                   8118: #
                   8119: 
1.620     albertel 8120:     unless ($env{'request.course.id'}) {
1.766     albertel 8121: 	if ($thisallowed eq 'A') {
                   8122: 	    return 'A';
1.814     raeburn  8123:         } elsif ($thisallowed eq 'B') {
                   8124:             return 'B';
1.766     albertel 8125: 	} else {
                   8126: 	    return '1';
                   8127: 	}
1.52      www      8128:     }
1.29      www      8129: 
1.52      www      8130: #
                   8131: # Now user is definitely in a course
                   8132: #
1.53      www      8133: 
                   8134: 
                   8135: # Course preferences
                   8136: 
                   8137:    if ($thisallowed=~/C/) {
1.620     albertel 8138:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8139:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8140:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8141: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8142: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8143: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8144: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8145: 			$env{'request.course.id'});
                   8146: 	   }
1.237     www      8147:            return '';
                   8148:        }
                   8149: 
1.620     albertel 8150:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8151: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8152: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8153: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8154: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8155: 			$env{'request.course.id'});
                   8156: 	   }
1.54      www      8157:            return '';
                   8158:        }
1.53      www      8159:    }
                   8160: 
                   8161: # Resource preferences
                   8162: 
                   8163:    if ($thisallowed=~/R/) {
1.620     albertel 8164:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8165:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8166: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8167: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8168: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8169: 	   }
                   8170: 	   return '';
1.54      www      8171:        }
1.53      www      8172:    }
1.30      www      8173: 
1.246     www      8174: # Restricted by state or randomout?
1.30      www      8175: 
1.52      www      8176:    if ($thisallowed=~/X/) {
1.620     albertel 8177:       if ($env{'acc.randomout'}) {
1.579     albertel 8178: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8179:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8180:             return ''; 
                   8181:          }
1.247     www      8182:       }
                   8183:       if (&condval($statecond)) {
1.52      www      8184: 	 return '2';
                   8185:       } else {
                   8186:          return '';
                   8187:       }
                   8188:    }
1.30      www      8189: 
1.766     albertel 8190:     if ($thisallowed eq 'A') {
                   8191: 	return 'A';
1.814     raeburn  8192:     } elsif ($thisallowed eq 'B') {
                   8193:         return 'B';
1.766     albertel 8194:     }
1.52      www      8195:    return 'F';
1.232     www      8196: }
1.1162    raeburn  8197: 
1.1172.2.13  raeburn  8198: # ------------------------------------------- Check construction space access
                   8199: 
                   8200: sub constructaccess {
                   8201:     my ($url,$setpriv)=@_;
                   8202: 
                   8203: # We do not allow editing of previous versions of files
                   8204:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8205: 
                   8206: # Get username and domain from URL
                   8207:     my ($ownername,$ownerdomain,$ownerhome);
                   8208: 
                   8209:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8210:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8211: 
                   8212: # The URL does not really point to any authorspace, forget it
                   8213:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8214: 
                   8215: # Now we need to see if the user has access to the authorspace of
                   8216: # $ownername at $ownerdomain
                   8217: 
                   8218:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8219: # Real author for this?
                   8220:        $ownerhome = $env{'user.home'};
                   8221:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8222:           return ($ownername,$ownerdomain,$ownerhome);
                   8223:        }
                   8224:     } else {
                   8225: # Co-author for this?
                   8226:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8227:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8228:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8229:             return ($ownername,$ownerdomain,$ownerhome);
                   8230:         }
                   8231:     }
                   8232: 
                   8233: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8234: # we might as well leave
                   8235:    unless ($setpriv) { return ''; }
                   8236: 
                   8237: # Backdoor access?
                   8238:     my $allowed=&allowed('eco',$ownerdomain);
                   8239: # Nope
                   8240:     unless ($allowed) { return ''; }
                   8241: # Looks like we may have access, but could be locked by the owner of the construction space
                   8242:     if ($allowed eq 'U') {
                   8243:         my %blocked=&get('environment',['domcoord.author'],
                   8244:                          $ownerdomain,$ownername);
                   8245: # Is blocked by owner
                   8246:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8247:     }
                   8248:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8249: # Grant temporary access
                   8250:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8251:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8252:         if (!$update) { $update = $then; }
                   8253:         my $refresh=$env{'user.refresh.time'};
                   8254:         if (!$refresh) { $refresh = $update; }
                   8255:         my $now = time;
                   8256:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8257:                            $now,'ca','constructaccess');
                   8258:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8259:         return($ownername,$ownerdomain,$ownerhome);
                   8260:     }
                   8261: # No business here
                   8262:     return '';
                   8263: }
                   8264: 
1.1172.2.66  raeburn  8265: # ----------------------------------------------------------- Content Blocking
                   8266: 
                   8267: {
                   8268: # Caches for faster Course Contents display where content blocking
                   8269: # is in operation (i.e., interval param set) for timed quiz.
                   8270: #
                   8271: # User for whom data are being temporarily cached.
                   8272: my $cacheduser='';
                   8273: # Cached blockers for this user (a hash of blocking items).
                   8274: my %cachedblockers=();
                   8275: # When the data were last cached.
                   8276: my $cachedlast='';
                   8277: 
                   8278: sub load_all_blockers {
                   8279:     my ($uname,$udom,$blocks)=@_;
                   8280:     if (($uname ne '') && ($udom ne '')) {
                   8281:         if (($cacheduser eq $uname.':'.$udom) &&
                   8282:             (abs($cachedlast-time)<5)) {
                   8283:             return;
                   8284:         }
                   8285:     }
                   8286:     $cachedlast=time;
                   8287:     $cacheduser=$uname.':'.$udom;
                   8288:     %cachedblockers = &get_commblock_resources($blocks);
                   8289: }
                   8290: 
1.1162    raeburn  8291: sub get_comm_blocks {
                   8292:     my ($cdom,$cnum) = @_;
                   8293:     if ($cdom eq '' || $cnum eq '') {
                   8294:         return unless ($env{'request.course.id'});
                   8295:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8296:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8297:     }
                   8298:     my %commblocks;
                   8299:     my $hashid=$cdom.'_'.$cnum;
                   8300:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8301:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8302:         %commblocks = %{$blocksref};
                   8303:     } else {
                   8304:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8305:         my $cachetime = 600;
                   8306:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8307:     }
                   8308:     return %commblocks;
                   8309: }
                   8310: 
1.1172.2.66  raeburn  8311: sub get_commblock_resources {
                   8312:     my ($blocks) = @_;
                   8313:     my %blockers = ();
                   8314:     return %blockers unless ($env{'request.course.id'});
                   8315:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8316:     my %commblocks;
                   8317:     if (ref($blocks) eq 'HASH') {
                   8318:         %commblocks = %{$blocks};
                   8319:     } else {
                   8320:         %commblocks = &get_comm_blocks();
                   8321:     }
1.1172.2.66  raeburn  8322:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8323:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8324:     return %blockers unless (ref($navmap));
                   8325:     my $now = time;
1.1162    raeburn  8326:     foreach my $block (keys(%commblocks)) {
                   8327:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8328:             my ($start,$end) = ($1,$2);
                   8329:             if ($start <= $now && $end >= $now) {
                   8330:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8331:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8332:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8333:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8334:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8335:                             }
                   8336:                         }
                   8337:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8338:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8339:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8340:                             }
                   8341:                         }
                   8342:                     }
                   8343:                 }
                   8344:             }
                   8345:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8346:             my $item = $1;
1.1163    raeburn  8347:             my @to_test;
1.1162    raeburn  8348:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8349:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8350:                     my @interval;
                   8351:                     my $type = 'map';
                   8352:                     if ($item eq 'course') {
                   8353:                         $type = 'course';
                   8354:                         @interval=&EXT("resource.0.interval");
                   8355:                     } else {
                   8356:                         if ($item =~ /___\d+___/) {
                   8357:                             $type = 'resource';
                   8358:                             @interval=&EXT("resource.0.interval",$item);
                   8359:                             if (ref($navmap)) {
                   8360:                                 my $res = $navmap->getBySymb($item);
                   8361:                                 push(@to_test,$res);
                   8362:                             }
1.1162    raeburn  8363:                         } else {
1.1172.2.66  raeburn  8364:                             my $mapsymb = &symbread($item,1);
                   8365:                             if ($mapsymb) {
                   8366:                                 if (ref($navmap)) {
                   8367:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8368:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8369:                                     foreach my $res (@to_test) {
                   8370:                                         my $symb = $res->symb();
                   8371:                                         next if ($symb eq $mapsymb);
                   8372:                                         if ($symb ne '') {
                   8373:                                             @interval=&EXT("resource.0.interval",$symb);
                   8374:                                             if ($interval[1] eq 'map') {
                   8375:                                                 last;
1.1162    raeburn  8376:                                             }
                   8377:                                         }
                   8378:                                     }
                   8379:                                 }
                   8380:                             }
                   8381:                         }
1.1172.2.66  raeburn  8382:                     }
                   8383:                     if ($interval[0] =~ /^\d+$/) {
                   8384:                         my $first_access;
                   8385:                         if ($type eq 'resource') {
                   8386:                             $first_access=&get_first_access($interval[1],$item);
                   8387:                         } elsif ($type eq 'map') {
                   8388:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8389:                         } else {
                   8390:                             $first_access=&get_first_access($interval[1]);
                   8391:                         }
                   8392:                         if ($first_access) {
                   8393:                             my $timesup = $first_access+$interval[0];
                   8394:                             if ($timesup > $now) {
                   8395:                                 my $activeblock;
                   8396:                                 foreach my $res (@to_test) {
                   8397:                                     if ($res->answerable()) {
                   8398:                                         $activeblock = 1;
                   8399:                                         last;
                   8400:                                     }
                   8401:                                 }
                   8402:                                 if ($activeblock) {
                   8403:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8404:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8405:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8406:                                          }
                   8407:                                     }
                   8408:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8409:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8410:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8411:                                         }
1.1162    raeburn  8412:                                     }
                   8413:                                 }
                   8414:                             }
                   8415:                         }
                   8416:                     }
                   8417:                 }
                   8418:             }
                   8419:         }
                   8420:     }
1.1172.2.66  raeburn  8421:     return %blockers;
1.1162    raeburn  8422: }
                   8423: 
1.1172.2.66  raeburn  8424: sub has_comm_blocking {
                   8425:     my ($priv,$symb,$uri,$blocks) = @_;
                   8426:     my @blockers;
                   8427:     return unless ($env{'request.course.id'});
                   8428:     return unless ($priv eq 'bre');
                   8429:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8430:     return if ($env{'request.state'} eq 'construct');
                   8431:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8432:     return unless (keys(%cachedblockers) > 0);
                   8433:     my (%possibles,@symbs);
                   8434:     if (!$symb) {
                   8435:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8436:     }
1.1172.2.66  raeburn  8437:     if ($symb) {
                   8438:         @symbs = ($symb);
                   8439:     } elsif (keys(%possibles)) {
                   8440:         @symbs = keys(%possibles);
                   8441:     }
                   8442:     my $noblock;
                   8443:     foreach my $symb (@symbs) {
                   8444:         last if ($noblock);
                   8445:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8446:         foreach my $block (keys(%cachedblockers)) {
                   8447:             if ($block =~ /^firstaccess____(.+)$/) {
                   8448:                 my $item = $1;
                   8449:                 if (($item eq $map) || ($item eq $symb)) {
                   8450:                     $noblock = 1;
                   8451:                     last;
                   8452:                 }
1.1162    raeburn  8453:             }
1.1172.2.66  raeburn  8454:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8455:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8456:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8457:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8458:                             push(@blockers,$block);
                   8459:                         }
                   8460:                     }
                   8461:                 }
                   8462:             }
                   8463:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8464:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8465:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8466:                         push(@blockers,$block);
                   8467:                     }
                   8468:                 }
1.1162    raeburn  8469:             }
                   8470:         }
                   8471:     }
1.1172.2.66  raeburn  8472:     return if ($noblock);
                   8473:     return @blockers;
                   8474: }
1.1162    raeburn  8475: }
                   8476: 
1.1172.2.66  raeburn  8477: # -------------------------------- Deversion and split uri into path an filename
                   8478: 
1.1133    foxr     8479: #
1.1172.2.66  raeburn  8480: #   Removes the version from a URI and
1.1133    foxr     8481: #   splits it in to its filename and path to the filename.
                   8482: #   Seems like File::Basename could have done this more clearly.
                   8483: #   Parameters:
                   8484: #      $uri   - input URI
                   8485: #   Returns:
                   8486: #     Two element list consisting of 
                   8487: #     $pathname  - the URI up to and excluding the trailing /
                   8488: #     $filename  - The part of the URI following the last /
                   8489: #  NOTE:
                   8490: #    Another realization of this is simply:
                   8491: #    use File::Basename;
                   8492: #    ...
                   8493: #    $uri = shift;
                   8494: #    $filename = basename($uri);
                   8495: #    $path     = dirname($uri);
                   8496: #    return ($filename, $path);
                   8497: #
                   8498: #     The implementation below is probably faster however.
                   8499: #
1.710     albertel 8500: sub split_uri_for_cond {
                   8501:     my $uri=&deversion(&declutter(shift));
                   8502:     my @uriparts=split(/\//,$uri);
                   8503:     my $filename=pop(@uriparts);
                   8504:     my $pathname=join('/',@uriparts);
                   8505:     return ($pathname,$filename);
                   8506: }
1.232     www      8507: # --------------------------------------------------- Is a resource on the map?
                   8508: 
                   8509: sub is_on_map {
1.710     albertel 8510:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8511:     #Trying to find the conditional for the file
1.620     albertel 8512:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8513: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8514:     if ($match) {
1.289     bowersj2 8515: 	return (1,$1);
                   8516:     } else {
1.434     www      8517: 	return (0,0);
1.289     bowersj2 8518:     }
1.12      www      8519: }
                   8520: 
1.427     www      8521: # --------------------------------------------------------- Get symb from alias
                   8522: 
                   8523: sub get_symb_from_alias {
                   8524:     my $symb=shift;
                   8525:     my ($map,$resid,$url)=&decode_symb($symb);
                   8526: # Already is a symb
                   8527:     if ($url) { return $symb; }
                   8528: # Must be an alias
                   8529:     my $aliassymb='';
                   8530:     my %bighash;
1.620     albertel 8531:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8532:                             &GDBM_READER(),0640)) {
                   8533:         my $rid=$bighash{'mapalias_'.$symb};
                   8534: 	if ($rid) {
                   8535: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8536: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8537: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8538: 	}
                   8539:         untie %bighash;
                   8540:     }
                   8541:     return $aliassymb;
                   8542: }
                   8543: 
1.12      www      8544: # ----------------------------------------------------------------- Define Role
                   8545: 
                   8546: sub definerole {
                   8547:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8548:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8549:     foreach my $role (split(':',$sysrole)) {
                   8550: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8551:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8552:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8553: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8554:                return "refused:s:$crole&$cqual"; 
                   8555:             }
                   8556:         }
1.191     harris41 8557:     }
1.800     albertel 8558:     foreach my $role (split(':',$domrole)) {
                   8559: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8560:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8561:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8562: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8563:                return "refused:d:$crole&$cqual"; 
                   8564:             }
                   8565:         }
1.191     harris41 8566:     }
1.800     albertel 8567:     foreach my $role (split(':',$courole)) {
                   8568: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8569:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8570:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8571: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8572:                return "refused:c:$crole&$cqual"; 
                   8573:             }
                   8574:         }
1.191     harris41 8575:     }
1.1172.2.84  raeburn  8576:     my $uhome;
                   8577:     if (($uname ne '') && ($udom ne '')) {
                   8578:         $uhome = &homeserver($uname,$udom);
                   8579:         return $uhome if ($uhome eq 'no_host');
                   8580:     } else {
                   8581:         $uname = $env{'user.name'};
                   8582:         $udom = $env{'user.domain'};
                   8583:         $uhome = $env{'user.home'};
                   8584:     }
1.620     albertel 8585:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8586:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8587:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8588:     return reply($command,$uhome);
1.12      www      8589:   } else {
                   8590:     return 'refused';
                   8591:   }
1.105     harris41 8592: }
                   8593: 
                   8594: # ---------------- Make a metadata query against the network of library servers
                   8595: 
                   8596: sub metadata_query {
1.1172.2.33  raeburn  8597:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8598:     my %rhash;
1.845     albertel 8599:     my %libserv = &all_library();
1.244     matthew  8600:     my @server_list = (defined($server_array) ? @$server_array
                   8601:                                               : keys(%libserv) );
                   8602:     for my $server (@server_list) {
1.1172.2.33  raeburn  8603:         my $domains = '';
                   8604:         if (ref($domains_hash) eq 'HASH') {
                   8605:             $domains = $domains_hash->{$server};    
                   8606:         }
1.118     harris41 8607: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8608: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8609: 	    $rhash{$server}=$reply;
                   8610: 	}
                   8611: 	else {
                   8612: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8613: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8614: 			     $server);
                   8615: 	    $rhash{$server}=$reply;
                   8616: 	}
1.112     harris41 8617:     }
1.118     harris41 8618:     return \%rhash;
1.240     www      8619: }
                   8620: 
                   8621: # ----------------------------------------- Send log queries and wait for reply
                   8622: 
                   8623: sub log_query {
                   8624:     my ($uname,$udom,$query,%filters)=@_;
                   8625:     my $uhome=&homeserver($uname,$udom);
                   8626:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8627:     my $uhost=&hostname($uhome);
1.800     albertel 8628:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8629:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8630:                        $uhome);
1.479     albertel 8631:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8632:     return get_query_reply($queryid);
                   8633: }
                   8634: 
1.818     raeburn  8635: # -------------------------- Update MySQL table for portfolio file
                   8636: 
                   8637: sub update_portfolio_table {
1.821     raeburn  8638:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8639:     if ($group ne '') {
                   8640:         $file_name =~s /^\Q$group\E//;
                   8641:     }
1.818     raeburn  8642:     my $homeserver = &homeserver($uname,$udom);
                   8643:     my $queryid=
1.821     raeburn  8644:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8645:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8646:     my $reply = &get_query_reply($queryid);
                   8647:     return $reply;
                   8648: }
                   8649: 
1.899     raeburn  8650: # -------------------------- Update MySQL allusers table
                   8651: 
                   8652: sub update_allusers_table {
                   8653:     my ($uname,$udom,$names) = @_;
                   8654:     my $homeserver = &homeserver($uname,$udom);
                   8655:     my $queryid=
                   8656:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8657:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8658:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8659:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8660:                'generation='.&escape($names->{'generation'}).'%%'.
                   8661:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8662:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8663:     return;
1.899     raeburn  8664: }
                   8665: 
1.508     raeburn  8666: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8667: 
                   8668: sub fetch_enrollment_query {
1.511     raeburn  8669:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8670:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8671:     my $maxtries = 1;
1.508     raeburn  8672:     if ($context eq 'automated') {
                   8673:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8674:         $sleep = 2;
                   8675:         $loopmax = 100;
1.547     raeburn  8676:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8677:     } else {
                   8678:         $homeserver = &homeserver($cnum,$dom);
                   8679:     }
1.838     albertel 8680:     my $host=&hostname($homeserver);
1.506     raeburn  8681:     my $cmd = '';
1.1000    raeburn  8682:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8683:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8684:     }
                   8685:     $cmd =~ s/%%$//;
                   8686:     $cmd = &escape($cmd);
                   8687:     my $query = 'fetchenrollment';
1.620     albertel 8688:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8689:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8690:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8691:         return 'error: '.$queryid;
                   8692:     }
1.1172.2.93  raeburn  8693:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8694:     my $tries = 1;
                   8695:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8696:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8697:         $tries ++;
                   8698:     }
1.526     raeburn  8699:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8700:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8701:     } else {
1.901     albertel 8702:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8703:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8704:             foreach my $line (@responses) {
                   8705:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8706:                 $$replyref{$key} = $value;
                   8707:             }
                   8708:         } else {
1.1117    foxr     8709:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8710:             foreach my $line (@responses) {
                   8711:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8712:                 $$replyref{$key} = $value;
                   8713:                 if ($value > 0) {
1.800     albertel 8714:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8715:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8716:                         my $destname = $pathname.'/'.$filename;
                   8717:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8718:                         if ($xml_classlist =~ /^error/) {
                   8719:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8720:                         } else {
1.1172.2.96  raeburn  8721:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8722:                                 print FILE &unescape($xml_classlist);
                   8723:                                 close(FILE);
1.526     raeburn  8724:                             } else {
                   8725:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8726:                             }
                   8727:                         }
                   8728:                     }
                   8729:                 }
                   8730:             }
                   8731:         }
                   8732:         return 'ok';
                   8733:     }
                   8734:     return 'error';
                   8735: }
                   8736: 
1.242     www      8737: sub get_query_reply {
1.1172.2.79  raeburn  8738:     my ($queryid,$sleep,$loopmax) = @_;
                   8739:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8740:         $sleep = 0.2;
                   8741:     }
                   8742:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8743:         $loopmax = 100;
                   8744:     }
1.1117    foxr     8745:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8746:     my $reply='';
1.1172.2.79  raeburn  8747:     for (1..$loopmax) {
                   8748: 	sleep($sleep);
1.240     www      8749:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8750: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8751: 		$reply = join('',<$fh>);
                   8752: 		close($fh);
1.240     www      8753: 	   } else { return 'error: reply_file_error'; }
1.242     www      8754:            return &unescape($reply);
                   8755: 	}
1.240     www      8756:     }
1.242     www      8757:     return 'timeout:'.$queryid;
1.240     www      8758: }
                   8759: 
                   8760: sub courselog_query {
1.241     www      8761: #
                   8762: # possible filters:
                   8763: # url: url or symb
                   8764: # username
                   8765: # domain
                   8766: # action: view, submit, grade
                   8767: # start: timestamp
                   8768: # end: timestamp
                   8769: #
1.240     www      8770:     my (%filters)=@_;
1.620     albertel 8771:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8772:     if ($filters{'url'}) {
                   8773: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8774:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8775:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8776:     }
1.620     albertel 8777:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8778:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8779:     return &log_query($cname,$cdom,'courselog',%filters);
                   8780: }
                   8781: 
                   8782: sub userlog_query {
1.858     raeburn  8783: #
                   8784: # possible filters:
                   8785: # action: log check role
                   8786: # start: timestamp
                   8787: # end: timestamp
                   8788: #
1.240     www      8789:     my ($uname,$udom,%filters)=@_;
                   8790:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8791: }
                   8792: 
1.506     raeburn  8793: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8794: 
                   8795: sub auto_run {
1.508     raeburn  8796:     my ($cnum,$cdom) = @_;
1.876     raeburn  8797:     my $response = 0;
                   8798:     my $settings;
                   8799:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8800:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8801:         $settings = $domconfig{'autoenroll'};
                   8802:         if ($settings->{'run'} eq '1') {
                   8803:             $response = 1;
                   8804:         }
                   8805:     } else {
1.934     raeburn  8806:         my $homeserver;
                   8807:         if (&is_course($cdom,$cnum)) {
                   8808:             $homeserver = &homeserver($cnum,$cdom);
                   8809:         } else {
                   8810:             $homeserver = &domain($cdom,'primary');
                   8811:         }
                   8812:         if ($homeserver ne 'no_host') {
                   8813:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8814:         }
1.876     raeburn  8815:     }
1.506     raeburn  8816:     return $response;
                   8817: }
1.776     albertel 8818: 
1.506     raeburn  8819: sub auto_get_sections {
1.508     raeburn  8820:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8821:     my $homeserver;
                   8822:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8823:         $homeserver = &homeserver($cnum,$cdom);
                   8824:     }
                   8825:     if (!defined($homeserver)) { 
                   8826:         if ($cdom =~ /^$match_domain$/) {
                   8827:             $homeserver = &domain($cdom,'primary');
                   8828:         }
                   8829:     }
                   8830:     my @secs;
                   8831:     if (defined($homeserver)) {
                   8832:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8833:         unless ($response eq 'refused') {
                   8834:             @secs = split(/:/,$response);
                   8835:         }
1.506     raeburn  8836:     }
                   8837:     return @secs;
                   8838: }
1.776     albertel 8839: 
1.506     raeburn  8840: sub auto_new_course {
1.1099    raeburn  8841:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8842:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8843:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8844:     return $response;
                   8845: }
1.776     albertel 8846: 
1.506     raeburn  8847: sub auto_validate_courseID {
1.508     raeburn  8848:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8849:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8850:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8851:     return $response;
                   8852: }
1.776     albertel 8853: 
1.1007    raeburn  8854: sub auto_validate_instcode {
1.1020    raeburn  8855:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8856:     my ($homeserver,$response);
                   8857:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8858:         $homeserver = &homeserver($cnum,$cdom);
                   8859:     }
                   8860:     if (!defined($homeserver)) {
                   8861:         if ($cdom =~ /^$match_domain$/) {
                   8862:             $homeserver = &domain($cdom,'primary');
                   8863:         }
                   8864:     }
1.1065    raeburn  8865:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8866:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8867:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8868:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8869: }
                   8870: 
1.506     raeburn  8871: sub auto_create_password {
1.873     raeburn  8872:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8873:     my ($homeserver,$response);
1.506     raeburn  8874:     my $create_passwd = 0;
                   8875:     my $authchk = '';
1.873     raeburn  8876:     if ($udom =~ /^$match_domain$/) {
                   8877:         $homeserver = &domain($udom,'primary');
                   8878:     }
                   8879:     if ($homeserver eq '') {
                   8880:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8881:             $homeserver = &homeserver($cnum,$cdom);
                   8882:         }
                   8883:     }
                   8884:     if ($homeserver eq '') {
                   8885:         $authchk = 'nodomain';
1.506     raeburn  8886:     } else {
1.873     raeburn  8887:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8888:         if ($response eq 'refused') {
                   8889:             $authchk = 'refused';
                   8890:         } else {
1.901     albertel 8891:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8892:         }
1.506     raeburn  8893:     }
                   8894:     return ($authparam,$create_passwd,$authchk);
                   8895: }
                   8896: 
1.706     raeburn  8897: sub auto_photo_permission {
                   8898:     my ($cnum,$cdom,$students) = @_;
                   8899:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8900:     my ($outcome,$perm_reqd,$conditions) = 
                   8901: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8902:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8903: 	return (undef,undef);
                   8904:     }
1.706     raeburn  8905:     return ($outcome,$perm_reqd,$conditions);
                   8906: }
                   8907: 
                   8908: sub auto_checkphotos {
                   8909:     my ($uname,$udom,$pid) = @_;
                   8910:     my $homeserver = &homeserver($uname,$udom);
                   8911:     my ($result,$resulttype);
                   8912:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8913: 				   &escape($uname).':'.&escape($pid),
                   8914: 				   $homeserver));
1.709     albertel 8915:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8916: 	return (undef,undef);
                   8917:     }
1.706     raeburn  8918:     if ($outcome) {
                   8919:         ($result,$resulttype) = split(/:/,$outcome);
                   8920:     } 
                   8921:     return ($result,$resulttype);
                   8922: }
                   8923: 
                   8924: sub auto_photochoice {
                   8925:     my ($cnum,$cdom) = @_;
                   8926:     my $homeserver = &homeserver($cnum,$cdom);
                   8927:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8928: 						       &escape($cdom),
                   8929: 						       $homeserver)));
1.709     albertel 8930:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8931: 	return (undef,undef);
                   8932:     }
1.706     raeburn  8933:     return ($update,$comment);
                   8934: }
                   8935: 
                   8936: sub auto_photoupdate {
                   8937:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8938:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8939:     my $host=&hostname($homeserver);
1.706     raeburn  8940:     my $cmd = '';
                   8941:     my $maxtries = 1;
1.800     albertel 8942:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8943:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8944:     }
                   8945:     $cmd =~ s/%%$//;
                   8946:     $cmd = &escape($cmd);
                   8947:     my $query = 'institutionalphotos';
                   8948:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8949:     unless ($queryid=~/^\Q$host\E\_/) {
                   8950:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8951:         return 'error: '.$queryid;
                   8952:     }
                   8953:     my $reply = &get_query_reply($queryid);
                   8954:     my $tries = 1;
                   8955:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8956:         $reply = &get_query_reply($queryid);
                   8957:         $tries ++;
                   8958:     }
                   8959:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8960:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8961:     } else {
                   8962:         my @responses = split(/:/,$reply);
                   8963:         my $outcome = shift(@responses); 
                   8964:         foreach my $item (@responses) {
                   8965:             my ($key,$value) = split(/=/,$item);
                   8966:             $$photo{$key} = $value;
                   8967:         }
                   8968:         return $outcome;
                   8969:     }
                   8970:     return 'error';
                   8971: }
                   8972: 
1.521     raeburn  8973: sub auto_instcode_format {
1.793     albertel 8974:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8975: 	$cat_order) = @_;
1.521     raeburn  8976:     my $courses = '';
1.772     raeburn  8977:     my @homeservers;
1.521     raeburn  8978:     if ($caller eq 'global') {
1.841     albertel 8979: 	my %servers = &get_servers($codedom,'library');
                   8980: 	foreach my $tryserver (keys(%servers)) {
                   8981: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8982: 		push(@homeservers,$tryserver);
                   8983: 	    }
1.584     raeburn  8984:         }
1.1022    raeburn  8985:     } elsif ($caller eq 'requests') {
                   8986:         if ($codedom =~ /^$match_domain$/) {
                   8987:             my $chome = &domain($codedom,'primary');
                   8988:             unless ($chome eq 'no_host') {
                   8989:                 push(@homeservers,$chome);
                   8990:             }
                   8991:         }
1.521     raeburn  8992:     } else {
1.772     raeburn  8993:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8994:     }
1.793     albertel 8995:     foreach my $code (keys(%{$instcodes})) {
                   8996:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8997:     }
                   8998:     chop($courses);
1.772     raeburn  8999:     my $ok_response = 0;
                   9000:     my $response;
                   9001:     while (@homeservers > 0 && $ok_response == 0) {
                   9002:         my $server = shift(@homeservers); 
                   9003:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9004:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9005:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9006: 		split(/:/,$response);
1.772     raeburn  9007:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9008:             push(@{$codetitles},&str2array($codetitles_str));
                   9009:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9010:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9011:             $ok_response = 1;
                   9012:         }
                   9013:     }
                   9014:     if ($ok_response) {
1.521     raeburn  9015:         return 'ok';
1.772     raeburn  9016:     } else {
                   9017:         return $response;
1.521     raeburn  9018:     }
                   9019: }
                   9020: 
1.792     raeburn  9021: sub auto_instcode_defaults {
                   9022:     my ($domain,$returnhash,$code_order) = @_;
                   9023:     my @homeservers;
1.841     albertel 9024: 
                   9025:     my %servers = &get_servers($domain,'library');
                   9026:     foreach my $tryserver (keys(%servers)) {
                   9027: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9028: 	    push(@homeservers,$tryserver);
                   9029: 	}
1.792     raeburn  9030:     }
1.841     albertel 9031: 
1.792     raeburn  9032:     my $response;
1.841     albertel 9033:     foreach my $server (@homeservers) {
1.792     raeburn  9034:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9035:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9036: 	
                   9037: 	foreach my $pair (split(/\&/,$response)) {
                   9038: 	    my ($name,$value)=split(/\=/,$pair);
                   9039: 	    if ($name eq 'code_order') {
                   9040: 		@{$code_order} = split(/\&/,&unescape($value));
                   9041: 	    } else {
                   9042: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9043: 	    }
                   9044: 	}
                   9045: 	return 'ok';
1.792     raeburn  9046:     }
1.841     albertel 9047: 
                   9048:     return $response;
1.1003    raeburn  9049: }
                   9050: 
                   9051: sub auto_possible_instcodes {
1.1007    raeburn  9052:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9053:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9054:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9055:         return;
                   9056:     }
1.1003    raeburn  9057:     my (@homeservers,$uhome);
                   9058:     if (defined(&domain($domain,'primary'))) {
                   9059:         $uhome=&domain($domain,'primary');
                   9060:         push(@homeservers,&domain($domain,'primary'));
                   9061:     } else {
                   9062:         my %servers = &get_servers($domain,'library');
                   9063:         foreach my $tryserver (keys(%servers)) {
                   9064:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9065:                 push(@homeservers,$tryserver);
                   9066:             }
                   9067:         }
                   9068:     }
                   9069:     my $response;
                   9070:     foreach my $server (@homeservers) {
                   9071:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9072:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9073:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9074:             split(':',$response);
                   9075:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9076:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9077:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9078:             my ($name,$value)=split('=',$item);
                   9079:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9080:         }
                   9081:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9082:             my ($name,$value)=split('=',$item);
                   9083:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9084:         }
                   9085:         return 'ok';
                   9086:     }
                   9087:     return $response;
                   9088: }
1.792     raeburn  9089: 
1.1010    raeburn  9090: sub auto_courserequest_checks {
                   9091:     my ($dom) = @_;
1.1020    raeburn  9092:     my ($homeserver,%validations);
                   9093:     if ($dom =~ /^$match_domain$/) {
                   9094:         $homeserver = &domain($dom,'primary');
                   9095:     }
                   9096:     unless ($homeserver eq 'no_host') {
                   9097:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9098:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9099:             my @items = split(/&/,$response);
                   9100:             foreach my $item (@items) {
                   9101:                 my ($key,$value) = split('=',$item);
                   9102:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9103:             }
                   9104:         }
                   9105:     }
1.1010    raeburn  9106:     return %validations; 
                   9107: }
                   9108: 
1.1020    raeburn  9109: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9110:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9111:     my ($homeserver,$response);
                   9112:     if ($dom =~ /^$match_domain$/) {
                   9113:         $homeserver = &domain($dom,'primary');
                   9114:     }
1.1172.2.43  raeburn  9115:     unless ($homeserver eq 'no_host') {
                   9116:         my $customdata;
                   9117:         if (ref($custominfo) eq 'HASH') {
                   9118:             $customdata = &freeze_escape($custominfo);
                   9119:         }
1.1020    raeburn  9120:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9121:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9122:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9123:                                     $customdata,$homeserver));
1.1020    raeburn  9124:     }
                   9125:     return $response;
                   9126: }
                   9127: 
1.777     albertel 9128: sub auto_validate_class_sec {
1.918     raeburn  9129:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9130:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9131:     my $ownerlist;
                   9132:     if (ref($owners) eq 'ARRAY') {
                   9133:         $ownerlist = join(',',@{$owners});
                   9134:     } else {
                   9135:         $ownerlist = $owners;
                   9136:     }
1.773     raeburn  9137:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9138:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9139:     return $response;
                   9140: }
                   9141: 
1.1172.2.94  raeburn  9142: sub auto_validate_instclasses {
                   9143:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9144:     my ($homeserver,%validations);
                   9145:     $homeserver = &homeserver($cnum,$cdom);
                   9146:     unless ($homeserver eq 'no_host') {
                   9147:         my $ownerlist;
                   9148:         if (ref($owners) eq 'ARRAY') {
                   9149:             $ownerlist = join(',',@{$owners});
                   9150:         } else {
                   9151:             $ownerlist = $owners;
                   9152:         }
                   9153:         if (ref($classesref) eq 'HASH') {
                   9154:             my $classes = &freeze_escape($classesref);
                   9155:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9156:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9157:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9158:                 my @items = split(/&/,$response);
                   9159:                 foreach my $item (@items) {
                   9160:                     my ($key,$value) = split('=',$item);
                   9161:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9162:                 }
                   9163:             }
                   9164:         }
                   9165:     }
                   9166:     return %validations;
                   9167: }
                   9168: 
1.1172.2.38  raeburn  9169: sub auto_crsreq_update {
                   9170:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9171:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9172:     my ($homeserver,%crsreqresponse);
                   9173:     if ($cdom =~ /^$match_domain$/) {
                   9174:         $homeserver = &domain($cdom,'primary');
                   9175:     }
                   9176:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9177:         my $info;
                   9178:         if (ref($inbound) eq 'HASH') {
                   9179:             $info = &freeze_escape($inbound);
                   9180:         }
                   9181:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9182:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9183:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9184:                             &escape($title).':'.&escape($code).':'.
                   9185:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9186:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9187:             my @items = split(/&/,$response);
                   9188:             foreach my $item (@items) {
                   9189:                 my ($key,$value) = split('=',$item);
                   9190:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9191:             }
                   9192:         }
                   9193:     }
                   9194:     return \%crsreqresponse;
                   9195: }
                   9196: 
1.1172.2.78  raeburn  9197: sub auto_export_grades {
                   9198:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9199:     my ($homeserver,%exportresponse);
                   9200:     if ($cdom =~ /^$match_domain$/) {
                   9201:         $homeserver = &domain($cdom,'primary');
                   9202:     }
                   9203:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9204:         my $info;
                   9205:         if (ref($inforef) eq 'HASH') {
                   9206:             $info = &freeze_escape($inforef);
                   9207:         }
                   9208:         if (ref($gradesref) eq 'HASH') {
                   9209:             my $grades = &freeze_escape($gradesref);
                   9210:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9211:                                 $info.':'.$grades,$homeserver);
                   9212:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9213:                 my @items = split(/&/,$response);
                   9214:                 foreach my $item (@items) {
                   9215:                     my ($key,$value) = split('=',$item);
                   9216:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9217:                 }
                   9218:             }
                   9219:         }
                   9220:     }
                   9221:     return \%exportresponse;
                   9222: }
                   9223: 
1.1172.2.68  raeburn  9224: sub check_instcode_cloning {
                   9225:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9226:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9227:         return;
                   9228:     }
                   9229:     my $canclone;
                   9230:     if (@{$code_order} > 0) {
                   9231:         my $instcoderegexp ='^';
                   9232:         my @clonecodes = split(/\&/,$cloner);
                   9233:         foreach my $item (@{$code_order}) {
                   9234:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9235:                 foreach my $pair (@clonecodes) {
                   9236:                     my ($key,$val) = split(/\=/,$pair,2);
                   9237:                     $val = &unescape($val);
                   9238:                     if ($key eq $item) {
                   9239:                         $instcoderegexp .= '('.$val.')';
                   9240:                         last;
                   9241:                     }
                   9242:                 }
                   9243:             } else {
                   9244:                 $instcoderegexp .= $codedefaults->{$item};
                   9245:             }
                   9246:         }
                   9247:         $instcoderegexp .= '$';
                   9248:         my (@from,@to);
                   9249:         eval {
                   9250:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9251:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9252:         };
                   9253:         if ((@from > 0) && (@to > 0)) {
                   9254:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9255:             if (!@diffs) {
                   9256:                 $canclone = 1;
                   9257:             }
                   9258:         }
                   9259:     }
                   9260:     return $canclone;
                   9261: }
                   9262: 
                   9263: sub default_instcode_cloning {
                   9264:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9265:     my (%codedefaults,@code_order,$canclone);
                   9266:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9267:         %codedefaults = %{$codedefaultsref};
                   9268:         @code_order = @{$codeorderref};
                   9269:     } elsif ($clonedom) {
                   9270:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9271:     }
                   9272:     if (($domdefclone) && (@code_order)) {
                   9273:         my @clonecodes = split(/\+/,$domdefclone);
                   9274:         my $instcoderegexp ='^';
                   9275:         foreach my $item (@code_order) {
                   9276:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9277:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9278:             } else {
                   9279:                 $instcoderegexp .= $codedefaults{$item};
                   9280:             }
                   9281:         }
                   9282:         $instcoderegexp .= '$';
                   9283:         my (@from,@to);
                   9284:         eval {
                   9285:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9286:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9287:         };
                   9288:         if ((@from > 0) && (@to > 0)) {
                   9289:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9290:             if (!@diffs) {
                   9291:                 $canclone = 1;
                   9292:             }
                   9293:         }
                   9294:     }
                   9295:     return $canclone;
                   9296: }
                   9297: 
1.679     raeburn  9298: # ------------------------------------------------------- Course Group routines
                   9299: 
                   9300: sub get_coursegroups {
1.809     raeburn  9301:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9302:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9303: }
                   9304: 
1.679     raeburn  9305: sub modify_coursegroup {
                   9306:     my ($cdom,$cnum,$groupsettings) = @_;
                   9307:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9308: }
                   9309: 
1.809     raeburn  9310: sub toggle_coursegroup_status {
                   9311:     my ($cdom,$cnum,$group,$action) = @_;
                   9312:     my ($from_namespace,$to_namespace);
                   9313:     if ($action eq 'delete') {
                   9314:         $from_namespace = 'coursegroups';
                   9315:         $to_namespace = 'deleted_groups';
                   9316:     } else {
                   9317:         $from_namespace = 'deleted_groups';
                   9318:         $to_namespace = 'coursegroups';
                   9319:     }
                   9320:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9321:     if (my $tmp = &error(%curr_group)) {
                   9322:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9323:         return ('read error',$tmp);
                   9324:     } else {
                   9325:         my %savedsettings = %curr_group; 
1.809     raeburn  9326:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9327:         my $deloutcome;
                   9328:         if ($result eq 'ok') {
1.809     raeburn  9329:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9330:         } else {
                   9331:             return ('write error',$result);
                   9332:         }
                   9333:         if ($deloutcome eq 'ok') {
                   9334:             return 'ok';
                   9335:         } else {
                   9336:             return ('delete error',$deloutcome);
                   9337:         }
                   9338:     }
                   9339: }
                   9340: 
1.679     raeburn  9341: sub modify_group_roles {
1.957     raeburn  9342:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9343:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9344:     my $role = 'gr/'.&escape($userprivs);
                   9345:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9346:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9347:     if ($result eq 'ok') {
                   9348:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9349:     }
1.679     raeburn  9350:     return $result;
                   9351: }
                   9352: 
                   9353: sub modify_coursegroup_membership {
                   9354:     my ($cdom,$cnum,$membership) = @_;
                   9355:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9356:     return $result;
                   9357: }
                   9358: 
1.682     raeburn  9359: sub get_active_groups {
                   9360:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9361:     my $now = time;
                   9362:     my %groups = ();
                   9363:     foreach my $key (keys(%env)) {
1.811     albertel 9364:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9365:             my ($start,$end) = split(/\./,$env{$key});
                   9366:             if (($end!=0) && ($end<$now)) { next; }
                   9367:             if (($start!=0) && ($start>$now)) { next; }
                   9368:             if ($1 eq $cdom && $2 eq $cnum) {
                   9369:                 $groups{$3} = $env{$key} ;
                   9370:             }
                   9371:         }
                   9372:     }
                   9373:     return %groups;
                   9374: }
                   9375: 
1.683     raeburn  9376: sub get_group_membership {
                   9377:     my ($cdom,$cnum,$group) = @_;
                   9378:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9379: }
                   9380: 
                   9381: sub get_users_groups {
                   9382:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9383:     my @usersgroups;
1.683     raeburn  9384:     my $cachetime=1800;
                   9385: 
                   9386:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9387:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9388:     if (defined($cached)) {
1.734     albertel 9389:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9390:     } else {  
                   9391:         $grouplist = '';
1.816     raeburn  9392:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9393:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9394:         my $access_end = $env{'course.'.$courseid.
                   9395:                               '.default_enrollment_end_date'};
                   9396:         my $now = time;
                   9397:         foreach my $key (keys(%roleshash)) {
                   9398:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9399:                 my $group = $1;
                   9400:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9401:                     my $start = $2;
                   9402:                     my $end = $1;
                   9403:                     if ($start == -1) { next; } # deleted from group
                   9404:                     if (($start!=0) && ($start>$now)) { next; }
                   9405:                     if (($end!=0) && ($end<$now)) {
                   9406:                         if ($access_end && $access_end < $now) {
                   9407:                             if ($access_end - $end < 86400) {
                   9408:                                 push(@usersgroups,$group);
1.733     raeburn  9409:                             }
                   9410:                         }
1.817     raeburn  9411:                         next;
1.733     raeburn  9412:                     }
1.817     raeburn  9413:                     push(@usersgroups,$group);
1.683     raeburn  9414:                 }
                   9415:             }
                   9416:         }
1.817     raeburn  9417:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9418:         $grouplist = join(':',@usersgroups);
                   9419:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9420:     }
1.733     raeburn  9421:     return @usersgroups;
1.683     raeburn  9422: }
                   9423: 
                   9424: sub devalidate_getgroups_cache {
                   9425:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9426:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9427: 
1.683     raeburn  9428:     my $hashid="$udom:$uname:$courseid";
                   9429:     &devalidate_cache_new('getgroups',$hashid);
                   9430: }
                   9431: 
1.12      www      9432: # ------------------------------------------------------------------ Plain Text
                   9433: 
                   9434: sub plaintext {
1.988     raeburn  9435:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9436:     if ($short =~ m{^cr/}) {
1.758     albertel 9437: 	return (split('/',$short))[-1];
                   9438:     }
1.742     raeburn  9439:     if (!defined($cid)) {
                   9440:         $cid = $env{'request.course.id'};
                   9441:     }
                   9442:     my %rolenames = (
1.1008    raeburn  9443:                       Course    => 'std',
                   9444:                       Community => 'alt1',
1.742     raeburn  9445:                     );
1.1037    raeburn  9446:     if ($cid ne '') {
                   9447:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9448:             unless ($forcedefault) {
                   9449:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9450:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9451:                 return &Apache::lonlocal::mt($roletext);
                   9452:             }
                   9453:         }
                   9454:     }
                   9455:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9456:         (defined($rolenames{$type})) && 
                   9457:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9458:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9459:     } elsif ($cid ne '') {
                   9460:         my $crstype = $env{'course.'.$cid.'.type'};
                   9461:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9462:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9463:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9464:         }
1.742     raeburn  9465:     }
1.1037    raeburn  9466:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9467: }
                   9468: 
                   9469: # ----------------------------------------------------------------- Assign Role
                   9470: 
                   9471: sub assignrole {
1.957     raeburn  9472:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9473:         $context)=@_;
1.21      www      9474:     my $mrole;
                   9475:     if ($role =~ /^cr\//) {
1.393     www      9476:         my $cwosec=$url;
1.811     albertel 9477:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9478: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9479:            my $refused = 1;
                   9480:            if ($context eq 'requestcourses') {
                   9481:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9482:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9483:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9484:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9485:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9486:                            if ($crsenv{'internal.courseowner'} eq
                   9487:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9488:                                $refused = '';
                   9489:                            }
                   9490:                        }
                   9491:                    }
                   9492:                }
                   9493:            }
                   9494:            if ($refused) {
                   9495:                &logthis('Refused custom assignrole: '.
                   9496:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9497:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9498:                return 'refused';
                   9499:            }
1.104     www      9500:         }
1.21      www      9501:         $mrole='cr';
1.678     raeburn  9502:     } elsif ($role =~ /^gr\//) {
                   9503:         my $cwogrp=$url;
1.811     albertel 9504:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9505:         unless (&allowed('mdg',$cwogrp)) {
                   9506:             &logthis('Refused group assignrole: '.
                   9507:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9508:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9509:             return 'refused';
                   9510:         }
                   9511:         $mrole='gr';
1.21      www      9512:     } else {
1.82      www      9513:         my $cwosec=$url;
1.811     albertel 9514:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9515:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9516:             my $refused;
                   9517:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9518:                 if (!(&allowed('c'.$role,$url))) {
                   9519:                     $refused = 1;
                   9520:                 }
                   9521:             } else {
                   9522:                 $refused = 1;
                   9523:             }
1.947     raeburn  9524:             if ($refused) {
1.1045    raeburn  9525:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9526:                 if (!$selfenroll && $context eq 'course') {
                   9527:                     my %crsenv;
                   9528:                     if ($role eq 'cc' || $role eq 'co') {
                   9529:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9530:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9531:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9532:                                 if ($crsenv{'internal.courseowner'} eq 
                   9533:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9534:                                     $refused = '';
                   9535:                                 }
                   9536:                             }
                   9537:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9538:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9539:                                 if ($crsenv{'internal.courseowner'} eq 
                   9540:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9541:                                     $refused = '';
                   9542:                                 }
                   9543:                             }
                   9544:                         }
                   9545:                     }
                   9546:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9547:                     $refused = '';
1.1017    raeburn  9548:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9549:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9550:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9551:                         my $wrongcc;
                   9552:                         if ($cnum =~ /^$match_community$/) {
                   9553:                             $wrongcc = 1 if ($role eq 'cc');
                   9554:                         } else {
                   9555:                             $wrongcc = 1 if ($role eq 'co');
                   9556:                         }
                   9557:                         unless ($wrongcc) {
                   9558:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9559:                             if ($crsenv{'internal.courseowner'} eq 
                   9560:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9561:                                 $refused = '';
                   9562:                             }
1.1017    raeburn  9563:                         }
                   9564:                     }
1.1172.2.9  raeburn  9565:                 } elsif ($context eq 'requestauthor') {
                   9566:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9567:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9568:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9569:                             $refused = '';
                   9570:                         } else {
                   9571:                             my %domdefaults = &get_domain_defaults($udom);
                   9572:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9573:                                 my $checkbystatus;
                   9574:                                 if ($env{'user.adv'}) {
                   9575:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9576:                                     if ($disposition eq 'automatic') {
                   9577:                                         $refused = '';
                   9578:                                     } elsif ($disposition eq '') {
                   9579:                                         $checkbystatus = 1;
                   9580:                                     }
                   9581:                                 } else {
                   9582:                                     $checkbystatus = 1;
                   9583:                                 }
                   9584:                                 if ($checkbystatus) {
                   9585:                                     if ($env{'environment.inststatus'}) {
                   9586:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9587:                                         foreach my $type (@inststatuses) {
                   9588:                                             if (($type ne '') &&
                   9589:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9590:                                                 $refused = '';
                   9591:                                             }
                   9592:                                         }
                   9593:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9594:                                         $refused = '';
                   9595:                                     }
                   9596:                                 }
                   9597:                             }
                   9598:                         }
                   9599:                     }
1.1017    raeburn  9600:                 }
                   9601:                 if ($refused) {
1.947     raeburn  9602:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9603:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9604: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9605:                     return 'refused';
                   9606:                 }
1.932     raeburn  9607:             }
1.1131    raeburn  9608:         } elsif ($role eq 'au') {
                   9609:             if ($url ne '/'.$udom.'/') {
                   9610:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9611:                          ' to assign author role for '.$uname.':'.$udom.
                   9612:                          ' in domain: '.$url.' refused (wrong domain).');
                   9613:                 return 'refused';
                   9614:             }
1.104     www      9615:         }
1.21      www      9616:         $mrole=$role;
                   9617:     }
1.620     albertel 9618:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9619:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9620:     if ($end) { $command.='_'.$end; }
1.21      www      9621:     if ($start) {
                   9622: 	if ($end) { 
1.81      www      9623:            $command.='_'.$start; 
1.21      www      9624:         } else {
1.81      www      9625:            $command.='_0_'.$start;
1.21      www      9626:         }
                   9627:     }
1.739     raeburn  9628:     my $origstart = $start;
                   9629:     my $origend = $end;
1.957     raeburn  9630:     my $delflag;
1.357     www      9631: # actually delete
                   9632:     if ($deleteflag) {
1.373     www      9633: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9634: # modify command to delete the role
1.620     albertel 9635:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9636:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9637: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9638: # set start and finish to negative values for userrolelog
                   9639:            $start=-1;
                   9640:            $end=-1;
1.957     raeburn  9641:            $delflag = 1;
1.357     www      9642:         }
                   9643:     }
                   9644: # send command
1.349     www      9645:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9646: # log new user role if status is ok
1.349     www      9647:     if ($answer eq 'ok') {
1.663     raeburn  9648: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9649:         if (($role eq 'cc') || ($role eq 'in') ||
                   9650:             ($role eq 'ep') || ($role eq 'ad') ||
                   9651:             ($role eq 'ta') || ($role eq 'st') ||
                   9652:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9653:             ($role eq 'co')) {
1.1172.2.13  raeburn  9654: # for course roles, perform group memberships changes triggered by role change.
                   9655:             unless ($role =~ /^gr/) {
                   9656:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9657:                                                  $origstart,$selfenroll,$context);
                   9658:             }
1.1172.2.9  raeburn  9659:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9660:                            $selfenroll,$context);
                   9661:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9662:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9663:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9664:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9665:                            $context);
                   9666:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9667:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9668:                              $context);
                   9669:         }
1.1053    raeburn  9670:         if ($role eq 'cc') {
                   9671:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9672:         }
1.349     www      9673:     }
                   9674:     return $answer;
1.169     harris41 9675: }
                   9676: 
1.1053    raeburn  9677: sub autoupdate_coowners {
                   9678:     my ($url,$end,$start,$uname,$udom) = @_;
                   9679:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9680:     if (($cdom ne '') && ($cnum ne '')) {
                   9681:         my $now = time;
                   9682:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9683:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9684:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9685:             my $instcode = $coursehash{'internal.coursecode'};
                   9686:             if ($instcode ne '') {
1.1056    raeburn  9687:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9688:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9689:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9690:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9691:                         if ($result eq 'valid') {
                   9692:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9693:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9694:                                     push(@newcoowners,$coowner);
                   9695:                                 }
                   9696:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9697:                                     push(@newcoowners,$uname.':'.$udom);
                   9698:                                 }
                   9699:                                 @newcoowners = sort(@newcoowners);
                   9700:                             } else {
                   9701:                                 push(@newcoowners,$uname.':'.$udom);
                   9702:                             }
                   9703:                         } else {
                   9704:                             if ($coursehash{'internal.co-owners'}) {
                   9705:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9706:                                     unless ($coowner eq $uname.':'.$udom) {
                   9707:                                         push(@newcoowners,$coowner);
                   9708:                                     }
                   9709:                                 }
                   9710:                                 unless (@newcoowners > 0) {
                   9711:                                     $delcoowners = 1;
                   9712:                                     $coowners = '';
                   9713:                                 }
                   9714:                             }
                   9715:                         }
                   9716:                         if (@newcoowners || $delcoowners) {
                   9717:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9718:                                             $delcoowners,@newcoowners);
                   9719:                         }
                   9720:                     }
                   9721:                 }
                   9722:             }
                   9723:         }
                   9724:     }
                   9725: }
                   9726: 
                   9727: sub store_coowners {
                   9728:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9729:     my $cid = $cdom.'_'.$cnum;
                   9730:     my ($coowners,$delresult,$putresult);
                   9731:     if (@newcoowners) {
                   9732:         $coowners = join(',',@newcoowners);
                   9733:         my %coownershash = (
                   9734:                             'internal.co-owners' => $coowners,
                   9735:                            );
                   9736:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9737:         if ($putresult eq 'ok') {
                   9738:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9739:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9740:             }
                   9741:         }
                   9742:     }
                   9743:     if ($delcoowners) {
                   9744:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9745:         if ($delresult eq 'ok') {
                   9746:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9747:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9748:             }
                   9749:         }
                   9750:     }
                   9751:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9752:         my %crsinfo =
                   9753:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9754:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9755:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9756:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9757:         }
                   9758:     }
                   9759: }
                   9760: 
1.169     harris41 9761: # -------------------------------------------------- Modify user authentication
1.197     www      9762: # Overrides without validation
                   9763: 
1.169     harris41 9764: sub modifyuserauth {
                   9765:     my ($udom,$uname,$umode,$upass)=@_;
                   9766:     my $uhome=&homeserver($uname,$udom);
1.197     www      9767:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9768:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9769:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9770:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9771:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9772: 		     &escape($upass),$uhome);
1.620     albertel 9773:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9774:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9775:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9776:     &log($udom,,$uname,$uhome,
1.620     albertel 9777:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9778:                                      $env{'user.name'}.', '.$umode.
1.197     www      9779:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9780:     unless ($reply eq 'ok') {
1.197     www      9781:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9782: 	return 'error: '.$reply;
                   9783:     }   
1.170     harris41 9784:     return 'ok';
1.80      www      9785: }
                   9786: 
1.81      www      9787: # --------------------------------------------------------------- Modify a user
1.80      www      9788: 
1.81      www      9789: sub modifyuser {
1.206     matthew  9790:     my ($udom,    $uname, $uid,
                   9791:         $umode,   $upass, $first,
                   9792:         $middle,  $last,  $gene,
1.1058    raeburn  9793:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9794:     $udom= &LONCAPA::clean_domain($udom);
                   9795:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9796:     my $showcandelete = 'none';
                   9797:     if (ref($candelete) eq 'ARRAY') {
                   9798:         if (@{$candelete} > 0) {
                   9799:             $showcandelete = join(', ',@{$candelete});
                   9800:         }
                   9801:     }
1.81      www      9802:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9803:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9804: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9805:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9806:                                      ' desiredhome not specified'). 
1.620     albertel 9807:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9808:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9809:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9810:     my $newuser;
                   9811:     if ($uhome eq 'no_host') {
                   9812:         $newuser = 1;
                   9813:     }
1.80      www      9814: # ----------------------------------------------------------------- Create User
1.406     albertel 9815:     if (($uhome eq 'no_host') && 
                   9816: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9817:         my $unhome='';
1.844     albertel 9818:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9819:             $unhome = $desiredhome;
1.620     albertel 9820: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9821: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9822:         } else { # load balancing routine for determining $unhome
1.81      www      9823:             my $loadm=10000000;
1.841     albertel 9824: 	    my %servers = &get_servers($udom,'library');
                   9825: 	    foreach my $tryserver (keys(%servers)) {
                   9826: 		my $answer=reply('load',$tryserver);
                   9827: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9828: 		    $loadm=$answer;
                   9829: 		    $unhome=$tryserver;
                   9830: 		}
1.80      www      9831: 	    }
                   9832:         }
                   9833:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9834: 	    return 'error: unable to find a home server for '.$uname.
                   9835:                    ' in domain '.$udom;
1.80      www      9836:         }
                   9837:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9838:                          &escape($upass),$unhome);
                   9839: 	unless ($reply eq 'ok') {
                   9840:             return 'error: '.$reply;
                   9841:         }   
1.230     stredwic 9842:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9843:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9844: 	    return 'error: unable verify users home machine.';
1.80      www      9845:         }
1.209     matthew  9846:     }   # End of creation of new user
1.80      www      9847: # ---------------------------------------------------------------------- Add ID
                   9848:     if ($uid) {
                   9849:        $uid=~tr/A-Z/a-z/;
                   9850:        my %uidhash=&idrget($udom,$uname);
1.196     www      9851:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9852:          && (!$forceid)) {
1.80      www      9853: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9854: 	      return 'error: user id "'.$uid.'" does not match '.
                   9855:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9856:           }
                   9857:        } else {
                   9858: 	  &idput($udom,($uname => $uid));
                   9859:        }
                   9860:     }
                   9861: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9862:     my @tmp=&get('environment',
1.899     raeburn  9863: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9864:                     'permanentemail','inststatus'],
1.134     albertel 9865: 		   $udom,$uname);
1.1075    raeburn  9866:     my (%names,%oldnames);
1.313     matthew  9867:     if ($tmp[0] =~ m/^error:.*/) { 
                   9868:         %names=(); 
                   9869:     } else {
                   9870:         %names = @tmp;
1.1075    raeburn  9871:         %oldnames = %names;
1.313     matthew  9872:     }
1.388     www      9873: #
1.1058    raeburn  9874: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9875: # of users did not contain them), do not overwrite existing values
                   9876: # unless field is in $candelete array ref.  
                   9877: #
                   9878: 
                   9879:     my @fields = ('firstname','middlename','lastname','generation',
                   9880:                   'permanentemail','id');
                   9881:     my %newvalues;
                   9882:     if (ref($candelete) eq 'ARRAY') {
                   9883:         foreach my $field (@fields) {
                   9884:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9885:                 if ($field eq 'firstname') {
                   9886:                     $names{$field} = $first;
                   9887:                 } elsif ($field eq 'middlename') {
                   9888:                     $names{$field} = $middle;
                   9889:                 } elsif ($field eq 'lastname') {
                   9890:                     $names{$field} = $last;
                   9891:                 } elsif ($field eq 'generation') { 
                   9892:                     $names{$field} = $gene;
                   9893:                 } elsif ($field eq 'permanentemail') {
                   9894:                     $names{$field} = $email;
                   9895:                 } elsif ($field eq 'id') {
                   9896:                     $names{$field}  = $uid;
                   9897:                 }
                   9898:             }
                   9899:         }
                   9900:     }
1.388     www      9901:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9902:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9903:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9904:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9905:     if ($email) {
                   9906:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9907:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9908:     }
1.899     raeburn  9909:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9910:     if (defined($inststatus)) {
                   9911:         $names{'inststatus'} = '';
                   9912:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9913:         if (ref($usertypes) eq 'HASH') {
                   9914:             my @okstatuses; 
                   9915:             foreach my $item (split(/:/,$inststatus)) {
                   9916:                 if (defined($usertypes->{$item})) {
                   9917:                     push(@okstatuses,$item);  
                   9918:                 }
                   9919:             }
                   9920:             if (@okstatuses) {
                   9921:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9922:             }
                   9923:         }
                   9924:     }
1.1075    raeburn  9925:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9926:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9927:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9928:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9929:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9930:     } else {
                   9931:         $logmsg .= ' during self creation';
                   9932:     }
1.1075    raeburn  9933:     my $changed;
                   9934:     if ($newuser) {
                   9935:         $changed = 1;
                   9936:     } else {
                   9937:         foreach my $field (@fields) {
                   9938:             if ($names{$field} ne $oldnames{$field}) {
                   9939:                 $changed = 1;
                   9940:                 last;
                   9941:             }
                   9942:         }
                   9943:     }
                   9944:     unless ($changed) {
                   9945:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9946:         &logthis($logmsg);
                   9947:         return 'ok';
                   9948:     }
                   9949:     my $reply = &put('environment', \%names, $udom,$uname);
                   9950:     if ($reply ne 'ok') { 
                   9951:         return 'error: '.$reply;
                   9952:     }
1.1087    raeburn  9953:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9954:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9955:     }
1.1075    raeburn  9956:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9957:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9958:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9959:     &logthis($logmsg);
1.134     albertel 9960:     return 'ok';
1.80      www      9961: }
                   9962: 
1.81      www      9963: # -------------------------------------------------------------- Modify student
1.80      www      9964: 
1.81      www      9965: sub modifystudent {
                   9966:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9967:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9968:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9969:     if (!$cid) {
1.620     albertel 9970: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9971: 	    return 'not_in_class';
                   9972: 	}
1.80      www      9973:     }
                   9974: # --------------------------------------------------------------- Make the user
1.81      www      9975:     my $reply=&modifyuser
1.209     matthew  9976: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9977:          $desiredhome,$email,$inststatus);
1.80      www      9978:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9979:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9980:     # student's environment
1.297     matthew  9981:     $uid = undef if (!$forceid);
1.455     albertel 9982:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9983: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9984:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9985:     return $reply;
                   9986: }
                   9987: 
                   9988: sub modify_student_enrollment {
1.1172.2.23  raeburn  9989:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9990:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9991:     my ($cdom,$cnum,$chome);
                   9992:     if (!$cid) {
1.620     albertel 9993: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9994: 	    return 'not_in_class';
                   9995: 	}
1.620     albertel 9996: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9997: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9998:     } else {
                   9999: 	($cdom,$cnum)=split(/_/,$cid);
                   10000:     }
1.620     albertel 10001:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10002:     if (!$chome) {
1.457     raeburn  10003: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10004:     }
1.455     albertel 10005:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10006:     # Make sure the user exists
1.81      www      10007:     my $uhome=&homeserver($uname,$udom);
                   10008:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10009: 	return 'error: no such user';
                   10010:     }
1.297     matthew  10011:     # Get student data if we were not given enough information
                   10012:     if (!defined($first)  || $first  eq '' || 
                   10013:         !defined($last)   || $last   eq '' || 
                   10014:         !defined($uid)    || $uid    eq '' || 
                   10015:         !defined($middle) || $middle eq '' || 
                   10016:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10017:         # They did not supply us with enough data to enroll the student, so
                   10018:         # we need to pick up more information.
1.297     matthew  10019:         my %tmp = &get('environment',
1.294     matthew  10020:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10021:                        ,$udom,$uname);
                   10022: 
1.800     albertel 10023:         #foreach my $key (keys(%tmp)) {
                   10024:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10025:         #}
1.294     matthew  10026:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10027:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10028:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10029:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10030:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10031:     }
1.556     albertel 10032:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10033:     my $user = "$uname:$udom";
                   10034:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10035:     my $reply=cput('classlist',
1.1148    raeburn  10036: 		   {$user => 
1.1172.2.76  raeburn  10037: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10038: 		   $cdom,$cnum);
1.1148    raeburn  10039:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10040:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10041:     } else { 
1.81      www      10042: 	return 'error: '.$reply;
                   10043:     }
1.297     matthew  10044:     # Add student role to user
1.83      www      10045:     my $uurl='/'.$cid;
1.81      www      10046:     $uurl=~s/\_/\//g;
                   10047:     if ($usec) {
                   10048: 	$uurl.='/'.$usec;
                   10049:     }
1.1148    raeburn  10050:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10051:                              $selfenroll,$context);
                   10052:     if ($result ne 'ok') {
                   10053:         if ($old_entry{$user} ne '') {
                   10054:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10055:         } else {
                   10056:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10057:         }
                   10058:     }
                   10059:     return $result; 
1.21      www      10060: }
                   10061: 
1.556     albertel 10062: sub format_name {
                   10063:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10064:     my $name;
                   10065:     if ($first ne 'lastname') {
                   10066: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10067:     } else {
                   10068: 	if ($lastname=~/\S/) {
                   10069: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10070: 	    $name=~s/\s+,/,/;
                   10071: 	} else {
                   10072: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10073: 	}
                   10074:     }
                   10075:     $name=~s/^\s+//;
                   10076:     $name=~s/\s+$//;
                   10077:     $name=~s/\s+/ /g;
                   10078:     return $name;
                   10079: }
                   10080: 
1.84      www      10081: # ------------------------------------------------- Write to course preferences
                   10082: 
                   10083: sub writecoursepref {
                   10084:     my ($courseid,%prefs)=@_;
                   10085:     $courseid=~s/^\///;
                   10086:     $courseid=~s/\_/\//g;
                   10087:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10088:     my $chome=homeserver($cnum,$cdomain);
                   10089:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10090: 	return 'error: no such course';
                   10091:     }
                   10092:     my $cstring='';
1.800     albertel 10093:     foreach my $pref (keys(%prefs)) {
                   10094: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10095:     }
1.84      www      10096:     $cstring=~s/\&$//;
                   10097:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10098: }
                   10099: 
                   10100: # ---------------------------------------------------------- Make/modify course
                   10101: 
                   10102: sub createcourse {
1.741     raeburn  10103:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10104:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10105:     $url=&declutter($url);
                   10106:     my $cid='';
1.1028    raeburn  10107:     if ($context eq 'requestcourses') {
                   10108:         my $can_create = 0;
                   10109:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10110:         if ($udom eq $ownerdom) {
                   10111:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10112:                                   $context)) {
                   10113:                 $can_create = 1;
                   10114:             }
                   10115:         } else {
                   10116:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10117:                                            $category);
                   10118:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10119:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10120:                 if (@curr > 0) {
                   10121:                     my @options = qw(approval validate autolimit);
                   10122:                     my $optregex = join('|',@options);
                   10123:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10124:                         $can_create = 1;
                   10125:                     }
                   10126:                 }
                   10127:             }
                   10128:         }
                   10129:         if ($can_create) {
                   10130:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10131:                 unless (&allowed('ccc',$udom)) {
                   10132:                     return 'refused'; 
                   10133:                 }
1.1017    raeburn  10134:             }
                   10135:         } else {
                   10136:             return 'refused';
                   10137:         }
1.1028    raeburn  10138:     } elsif (!&allowed('ccc',$udom)) {
                   10139:         return 'refused';
1.84      www      10140:     }
1.1011    raeburn  10141: # --------------------------------------------------------------- Get Unique ID
                   10142:     my $uname;
                   10143:     if ($cnum =~ /^$match_courseid$/) {
                   10144:         my $chome=&homeserver($cnum,$udom,'true');
                   10145:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10146:             $uname = $cnum;
                   10147:         } else {
1.1038    raeburn  10148:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10149:         }
                   10150:     } else {
1.1038    raeburn  10151:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10152:     }
                   10153:     return $uname if ($uname =~ /^error/);
                   10154: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10155:     if (!defined($course_server)) {
                   10156:         if (defined(&domain($udom,'primary'))) {
                   10157:             $course_server = &domain($udom,'primary');
                   10158:         } else {
                   10159:             $course_server = $env{'user.home'}; 
                   10160:         }
                   10161:     }
                   10162:     my %host_servers =
                   10163:         &Apache::lonnet::get_servers($udom,'library');
                   10164:     unless ($host_servers{$course_server}) {
                   10165:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10166:     }
1.84      www      10167: # ------------------------------------------------------------- Make the course
                   10168:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10169:                       $course_server);
1.84      www      10170:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10171:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10172:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10173: 	return 'error: no such course';
                   10174:     }
1.271     www      10175: # ----------------------------------------------------------------- Course made
1.516     raeburn  10176: # log existence
1.1029    raeburn  10177:     my $now = time;
1.918     raeburn  10178:     my $newcourse = {
                   10179:                     $udom.'_'.$uname => {
1.921     raeburn  10180:                                      description => $description,
                   10181:                                      inst_code   => $inst_code,
                   10182:                                      owner       => $course_owner,
                   10183:                                      type        => $crstype,
1.1029    raeburn  10184:                                      creator     => $env{'user.name'}.':'.
                   10185:                                                     $env{'user.domain'},
                   10186:                                      created     => $now,
                   10187:                                      context     => $context,
1.918     raeburn  10188:                                                 },
                   10189:                     };
1.921     raeburn  10190:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10191: # set toplevel url
1.271     www      10192:     my $topurl=$url;
                   10193:     unless ($nonstandard) {
                   10194: # ------------------------------------------ For standard courses, make top url
                   10195:         my $mapurl=&clutter($url);
1.278     www      10196:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10197:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10198: <map>
                   10199: <resource id="1" type="start"></resource>
                   10200: <resource id="2" src="$mapurl"></resource>
                   10201: <resource id="3" type="finish"></resource>
                   10202: <link index="1" from="1" to="2"></link>
                   10203: <link index="2" from="2" to="3"></link>
                   10204: </map>
                   10205: ENDINITMAP
                   10206:         $topurl=&declutter(
1.638     albertel 10207:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10208:                           );
                   10209:     }
                   10210: # ----------------------------------------------------------- Write preferences
1.84      www      10211:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10212:                      ('description'              => $description,
                   10213:                       'url'                      => $topurl,
                   10214:                       'internal.creator'         => $env{'user.name'}.':'.
                   10215:                                                     $env{'user.domain'},
                   10216:                       'internal.created'         => $now,
                   10217:                       'internal.creationcontext' => $context)
                   10218:                     );
1.84      www      10219:     return '/'.$udom.'/'.$uname;
                   10220: }
                   10221: 
1.1011    raeburn  10222: # ------------------------------------------------------------------- Create ID
                   10223: sub generate_coursenum {
1.1038    raeburn  10224:     my ($udom,$crstype) = @_;
1.1011    raeburn  10225:     my $domdesc = &domain($udom);
                   10226:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10227:     my $first;
                   10228:     if ($crstype eq 'Community') {
                   10229:         $first = '0';
                   10230:     } else {
                   10231:         $first = int(1+rand(9)); 
                   10232:     } 
                   10233:     my $uname=$first.
1.1011    raeburn  10234:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10235:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10236:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10237: # ----------------------------------------------- Make sure that does not exist
                   10238:     my $uhome=&homeserver($uname,$udom,'true');
                   10239:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10240:         if ($crstype eq 'Community') {
                   10241:             $first = '0';
                   10242:         } else {
                   10243:             $first = int(1+rand(9));
                   10244:         }
                   10245:         $uname=$first.
1.1011    raeburn  10246:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10247:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10248:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10249:         $uhome=&homeserver($uname,$udom,'true');
                   10250:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10251:             return 'error: unable to generate unique course-ID';
                   10252:         }
                   10253:     }
                   10254:     return $uname;
                   10255: }
                   10256: 
1.813     albertel 10257: sub is_course {
1.1167    droeschl 10258:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10259:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10260:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10261:     my $uhome=&homeserver($cnum,$cdom);
                   10262:     my $iscourse;
                   10263:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10264:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10265:     } else {
                   10266:         my $hashid = $cdom.':'.$cnum;
                   10267:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10268:         unless (defined($cached)) {
                   10269:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10270:                                         $cnum,undef,undef,'.');
                   10271:             $iscourse = 0;
                   10272:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10273:                 $iscourse = 1;
                   10274:             }
                   10275:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10276:         }
                   10277:     }
                   10278:     return unless($iscourse);
1.1167    droeschl 10279:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10280: }
                   10281: 
1.1015    raeburn  10282: sub store_userdata {
                   10283:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10284:     my $result;
1.1016    raeburn  10285:     if ($datakey ne '') {
1.1013    raeburn  10286:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10287:             if ($udom eq '' || $uname eq '') {
                   10288:                 $udom = $env{'user.domain'};
                   10289:                 $uname = $env{'user.name'};
                   10290:             }
                   10291:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10292:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10293:                 $result = 'error: no_host';
                   10294:             } else {
                   10295:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10296:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10297: 
                   10298:                 my $namevalue='';
                   10299:                 foreach my $key (keys(%{$storehash})) {
                   10300:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10301:                 }
                   10302:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10303:                 unless ($namespace eq 'courserequests') {
                   10304:                     $datakey = &escape($datakey);
                   10305:                 }
1.1105    raeburn  10306:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10307:                                   $namevalue,$uhome);
1.1013    raeburn  10308:             }
                   10309:         } else {
                   10310:             $result = 'error: data to store was not a hash reference'; 
                   10311:         }
                   10312:     } else {
                   10313:         $result= 'error: invalid requestkey'; 
                   10314:     }
                   10315:     return $result;
                   10316: }
                   10317: 
1.21      www      10318: # ---------------------------------------------------------- Assign Custom Role
                   10319: 
                   10320: sub assigncustomrole {
1.957     raeburn  10321:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10322:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10323:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10324: }
                   10325: 
                   10326: # ----------------------------------------------------------------- Revoke Role
                   10327: 
                   10328: sub revokerole {
1.957     raeburn  10329:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10330:     my $now=time;
1.965     raeburn  10331:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10332: }
                   10333: 
                   10334: # ---------------------------------------------------------- Revoke Custom Role
                   10335: 
                   10336: sub revokecustomrole {
1.957     raeburn  10337:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10338:     my $now=time;
1.357     www      10339:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10340:            $deleteflag,$selfenroll,$context);
1.17      www      10341: }
                   10342: 
1.533     banghart 10343: # ------------------------------------------------------------ Disk usage
1.535     albertel 10344: sub diskusage {
1.955     raeburn  10345:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10346:     $directorypath =~ s/\/$//;
                   10347:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10348:                        .&escape($getpropath).':'.&escape($uname).':'
                   10349:                        .&escape($udom),homeserver($uname,$udom));
                   10350:     if ($listing eq 'unknown_cmd') {
                   10351:         if ($getpropath) {
                   10352:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10353:         }
                   10354:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10355:     }
1.514     albertel 10356:     return $listing;
1.512     banghart 10357: }
                   10358: 
1.566     banghart 10359: sub is_locked {
1.1096    raeburn  10360:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10361:     my @check;
                   10362:     my $is_locked;
1.1093    raeburn  10363:     push (@check,$file_name);
1.613     albertel 10364:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10365: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10366:     my ($tmp)=keys(%locked);
                   10367:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10368:     
1.566     banghart 10369:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10370:         $is_locked = 'false';
                   10371:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10372:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10373:                $is_locked = 'true';
1.1096    raeburn  10374:                if (ref($which) eq 'ARRAY') {
                   10375:                    push(@{$which},$entry);
                   10376:                } else {
                   10377:                    last;
                   10378:                }
1.745     raeburn  10379:            }
                   10380:        }
1.566     banghart 10381:     } else {
                   10382:         $is_locked = 'false';
                   10383:     }
1.1093    raeburn  10384:     return $is_locked;
1.566     banghart 10385: }
                   10386: 
1.759     albertel 10387: sub declutter_portfile {
                   10388:     my ($file) = @_;
1.833     albertel 10389:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10390:     return $file;
                   10391: }
                   10392: 
1.559     banghart 10393: # ------------------------------------------------------------- Mark as Read Only
                   10394: 
                   10395: sub mark_as_readonly {
                   10396:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10397:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10398:     my ($tmp)=keys(%current_permissions);
                   10399:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10400:     foreach my $file (@{$files}) {
1.759     albertel 10401: 	$file = &declutter_portfile($file);
1.561     banghart 10402:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10403:     }
1.613     albertel 10404:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10405:     return;
                   10406: }
                   10407: 
1.572     banghart 10408: # ------------------------------------------------------------Save Selected Files
                   10409: 
                   10410: sub save_selected_files {
                   10411:     my ($user, $path, @files) = @_;
                   10412:     my $filename = $user."savedfiles";
1.573     banghart 10413:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10414:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10415:     foreach my $file (@files) {
1.620     albertel 10416:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10417:     }
                   10418:     foreach my $file (@other_files) {
1.574     banghart 10419:         print (OUT $file."\n");
1.572     banghart 10420:     }
1.574     banghart 10421:     close (OUT);
1.572     banghart 10422:     return 'ok';
                   10423: }
                   10424: 
1.574     banghart 10425: sub clear_selected_files {
                   10426:     my ($user) = @_;
                   10427:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10428:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10429:     print (OUT undef);
                   10430:     close (OUT);
                   10431:     return ("ok");    
                   10432: }
                   10433: 
1.572     banghart 10434: sub files_in_path {
                   10435:     my ($user, $path) = @_;
                   10436:     my $filename = $user."savedfiles";
                   10437:     my %return_files;
1.1172.2.96  raeburn  10438:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10439:     while (my $line_in = <IN>) {
1.574     banghart 10440:         chomp ($line_in);
                   10441:         my @paths_and_file = split (m!/!, $line_in);
                   10442:         my $file_part = pop (@paths_and_file);
                   10443:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10444:         $path_part.='/';
                   10445:         my $path_and_file = $path_part.$file_part;
                   10446:         if ($path_part eq $path) {
                   10447:             $return_files{$file_part}= 'selected';
                   10448:         }
                   10449:     }
1.574     banghart 10450:     close (IN);
                   10451:     return (\%return_files);
1.572     banghart 10452: }
                   10453: 
                   10454: # called in portfolio select mode, to show files selected NOT in current directory
                   10455: sub files_not_in_path {
                   10456:     my ($user, $path) = @_;
                   10457:     my $filename = $user."savedfiles";
                   10458:     my @return_files;
                   10459:     my $path_part;
1.1172.2.96  raeburn  10460:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10461:     while (my $line = <IN>) {
1.572     banghart 10462:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10463:         my @paths_and_file = split(m|/|, $line);
                   10464:         my $file_part = pop(@paths_and_file);
                   10465:         chomp($file_part);
                   10466:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10467:         $path_part .= '/';
                   10468:         my $path_and_file = $path_part.$file_part;
                   10469:         if ($path_part ne $path) {
1.800     albertel 10470:             push(@return_files, ($path_and_file));
1.572     banghart 10471:         }
                   10472:     }
1.800     albertel 10473:     close(OUT);
1.574     banghart 10474:     return (@return_files);
1.572     banghart 10475: }
                   10476: 
1.745     raeburn  10477: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10478: 
1.745     raeburn  10479: sub get_portfile_permissions {
                   10480:     my ($domain,$user) = @_;
1.613     albertel 10481:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10482:     my ($tmp)=keys(%current_permissions);
                   10483:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10484:     return \%current_permissions;
                   10485: }
                   10486: 
                   10487: #---------------------------------------------Get portfolio file access controls
                   10488: 
1.749     raeburn  10489: sub get_access_controls {
1.745     raeburn  10490:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10491:     my %access;
                   10492:     my $real_file = $file;
                   10493:     $file =~ s/\.meta$//;
1.745     raeburn  10494:     if (defined($file)) {
1.749     raeburn  10495:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10496:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10497:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10498:             }
                   10499:         }
1.745     raeburn  10500:     } else {
1.749     raeburn  10501:         foreach my $key (keys(%{$current_permissions})) {
                   10502:             if ($key =~ /\0accesscontrol$/) {
                   10503:                 if (defined($group)) {
                   10504:                     if ($key !~ m-^\Q$group\E/-) {
                   10505:                         next;
                   10506:                     }
                   10507:                 }
                   10508:                 my ($fullpath) = split(/\0/,$key);
                   10509:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10510:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10511:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10512:                     }
                   10513:                 }
                   10514:             }
                   10515:         }
                   10516:     }
                   10517:     return %access;
                   10518: }
                   10519: 
                   10520: sub modify_access_controls {
                   10521:     my ($file_name,$changes,$domain,$user)=@_;
                   10522:     my ($outcome,$deloutcome);
                   10523:     my %store_permissions;
                   10524:     my %new_values;
                   10525:     my %new_control;
                   10526:     my %translation;
                   10527:     my @deletions = ();
                   10528:     my $now = time;
                   10529:     if (exists($$changes{'activate'})) {
                   10530:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10531:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10532:             my $numnew = scalar(@newitems);
                   10533:             for (my $i=0; $i<$numnew; $i++) {
                   10534:                 my $newkey = $newitems[$i];
                   10535:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10536:                 if ($newkey =~ /^\d+:/) { 
                   10537:                     $newkey =~ s/^(\d+)/$newid/;
                   10538:                     $translation{$1} = $newid;
                   10539:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10540:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10541:                     $translation{$1} = $newid;
                   10542:                 }
1.749     raeburn  10543:                 $new_values{$file_name."\0".$newkey} = 
                   10544:                                           $$changes{'activate'}{$newitems[$i]};
                   10545:                 $new_control{$newkey} = $now;
                   10546:             }
                   10547:         }
                   10548:     }
                   10549:     my %todelete;
                   10550:     my %changed_items;
                   10551:     foreach my $action ('delete','update') {
                   10552:         if (exists($$changes{$action})) {
                   10553:             if (ref($$changes{$action}) eq 'HASH') {
                   10554:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10555:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10556:                     if ($action eq 'delete') { 
                   10557:                         $todelete{$itemnum} = 1;
                   10558:                     } else {
                   10559:                         $changed_items{$itemnum} = $key;
                   10560:                     }
                   10561:                 }
1.745     raeburn  10562:             }
                   10563:         }
1.749     raeburn  10564:     }
                   10565:     # get lock on access controls for file.
                   10566:     my $lockhash = {
                   10567:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10568:                                                        ':'.$env{'user.domain'},
                   10569:                    }; 
                   10570:     my $tries = 0;
                   10571:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10572:    
1.1172.2.79  raeburn  10573:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10574:         $tries ++;
1.1172.2.79  raeburn  10575:         sleep(0.1);
1.749     raeburn  10576:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10577:     }
                   10578:     if ($gotlock eq 'ok') {
                   10579:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10580:         my ($tmp)=keys(%curr_permissions);
                   10581:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10582:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10583:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10584:             if (ref($curr_controls) eq 'HASH') {
                   10585:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10586:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10587:                     if (defined($todelete{$itemnum})) {
                   10588:                         push(@deletions,$file_name."\0".$control_item);
                   10589:                     } else {
                   10590:                         if (defined($changed_items{$itemnum})) {
                   10591:                             $new_control{$changed_items{$itemnum}} = $now;
                   10592:                             push(@deletions,$file_name."\0".$control_item);
                   10593:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10594:                         } else {
                   10595:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10596:                         }
                   10597:                     }
1.745     raeburn  10598:                 }
                   10599:             }
                   10600:         }
1.970     raeburn  10601:         my ($group);
                   10602:         if (&is_course($domain,$user)) {
                   10603:             ($group,my $file) = split(/\//,$file_name,2);
                   10604:         }
1.749     raeburn  10605:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10606:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10607:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10608:         #  remove lock
                   10609:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10610:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10611:         my $sqlresult =
1.970     raeburn  10612:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10613:                                     $group);
1.749     raeburn  10614:     } else {
                   10615:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10616:     }
1.749     raeburn  10617:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10618: }
                   10619: 
1.827     raeburn  10620: sub make_public_indefinitely {
                   10621:     my ($requrl) = @_;
                   10622:     my $now = time;
                   10623:     my $action = 'activate';
                   10624:     my $aclnum = 0;
                   10625:     if (&is_portfolio_url($requrl)) {
                   10626:         my (undef,$udom,$unum,$file_name,$group) =
                   10627:             &parse_portfolio_url($requrl);
                   10628:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10629:         my %access_controls = &get_access_controls($current_perms,
                   10630:                                                    $group,$file_name);
                   10631:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10632:             my ($num,$scope,$end,$start) = 
                   10633:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10634:             if ($scope eq 'public') {
                   10635:                 if ($start <= $now && $end == 0) {
                   10636:                     $action = 'none';
                   10637:                 } else {
                   10638:                     $action = 'update';
                   10639:                     $aclnum = $num;
                   10640:                 }
                   10641:                 last;
                   10642:             }
                   10643:         }
                   10644:         if ($action eq 'none') {
                   10645:              return 'ok';
                   10646:         } else {
                   10647:             my %changes;
                   10648:             my $newend = 0;
                   10649:             my $newstart = $now;
                   10650:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10651:             $changes{$action}{$newkey} = {
                   10652:                 type => 'public',
                   10653:                 time => {
                   10654:                     start => $newstart,
                   10655:                     end   => $newend,
                   10656:                 },
                   10657:             };
                   10658:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10659:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10660:             return $outcome;
                   10661:         }
                   10662:     } else {
                   10663:         return 'invalid';
                   10664:     }
                   10665: }
                   10666: 
1.745     raeburn  10667: #------------------------------------------------------Get Marked as Read Only
                   10668: 
                   10669: sub get_marked_as_readonly {
                   10670:     my ($domain,$user,$what,$group) = @_;
                   10671:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10672:     my @readonly_files;
1.629     banghart 10673:     my $cmp1=$what;
                   10674:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10675:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10676:         if (defined($group)) {
                   10677:             if ($file_name !~ m-^\Q$group\E/-) {
                   10678:                 next;
                   10679:             }
                   10680:         }
1.561     banghart 10681:         if (ref($value) eq "ARRAY"){
                   10682:             foreach my $stored_what (@{$value}) {
1.629     banghart 10683:                 my $cmp2=$stored_what;
1.759     albertel 10684:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10685:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10686:                 }
1.629     banghart 10687:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10688:                     push(@readonly_files, $file_name);
1.745     raeburn  10689:                     last;
1.563     banghart 10690:                 } elsif (!defined($what)) {
                   10691:                     push(@readonly_files, $file_name);
1.745     raeburn  10692:                     last;
1.561     banghart 10693:                 }
                   10694:             }
1.745     raeburn  10695:         }
1.561     banghart 10696:     }
                   10697:     return @readonly_files;
                   10698: }
1.577     banghart 10699: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10700: 
1.577     banghart 10701: sub get_marked_as_readonly_hash {
1.745     raeburn  10702:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10703:     my %readonly_files;
1.745     raeburn  10704:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10705:         if (defined($group)) {
                   10706:             if ($file_name !~ m-^\Q$group\E/-) {
                   10707:                 next;
                   10708:             }
                   10709:         }
1.577     banghart 10710:         if (ref($value) eq "ARRAY"){
                   10711:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10712:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10713:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10714:                         if ($lock_descriptor eq 'graded') {
                   10715:                             $readonly_files{$file_name} = 'graded';
                   10716:                         } elsif ($lock_descriptor eq 'handback') {
                   10717:                             $readonly_files{$file_name} = 'handback';
                   10718:                         } else {
                   10719:                             if (!exists($readonly_files{$file_name})) {
                   10720:                                 $readonly_files{$file_name} = 'locked';
                   10721:                             }
                   10722:                         }
1.745     raeburn  10723:                     }
1.750     banghart 10724:                 } 
1.577     banghart 10725:             }
                   10726:         } 
                   10727:     }
                   10728:     return %readonly_files;
                   10729: }
1.559     banghart 10730: # ------------------------------------------------------------ Unmark as Read Only
                   10731: 
                   10732: sub unmark_as_readonly {
1.629     banghart 10733:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10734:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10735:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10736:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10737:     my $symb_crs = $what;
                   10738:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10739:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10740:     my ($tmp)=keys(%current_permissions);
                   10741:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10742:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10743:     foreach my $file (@readonly_files) {
1.759     albertel 10744: 	my $clean_file = &declutter_portfile($file);
                   10745: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10746: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10747:         my @new_locks;
                   10748:         my @del_keys;
                   10749:         if (ref($current_locks) eq "ARRAY"){
                   10750:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10751:                 my $compare=$locker;
1.749     raeburn  10752:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10753:                     $compare=join('',@{$locker});
1.746     raeburn  10754:                     if ($compare ne $symb_crs) {
                   10755:                         push(@new_locks, $locker);
                   10756:                     }
1.563     banghart 10757:                 }
                   10758:             }
1.650     albertel 10759:             if (scalar(@new_locks) > 0) {
1.563     banghart 10760:                 $current_permissions{$file} = \@new_locks;
                   10761:             } else {
                   10762:                 push(@del_keys, $file);
1.613     albertel 10763:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10764:                 delete($current_permissions{$file});
1.563     banghart 10765:             }
                   10766:         }
1.561     banghart 10767:     }
1.613     albertel 10768:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10769:     return;
                   10770: }
1.512     banghart 10771: 
1.17      www      10772: # ------------------------------------------------------------ Directory lister
                   10773: 
                   10774: sub dirlist {
1.955     raeburn  10775:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10776:     $uri=~s/^\///;
                   10777:     $uri=~s/\/$//;
1.253     stredwic 10778:     my ($udom, $uname);
1.955     raeburn  10779:     if ($getuserdir) {
1.253     stredwic 10780:         $udom = $userdomain;
                   10781:         $uname = $username;
1.955     raeburn  10782:     } else {
                   10783:         (undef,$udom,$uname)=split(/\//,$uri);
                   10784:         if(defined($userdomain)) {
                   10785:             $udom = $userdomain;
                   10786:         }
                   10787:         if(defined($username)) {
                   10788:             $uname = $username;
                   10789:         }
1.253     stredwic 10790:     }
1.955     raeburn  10791:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10792: 
1.955     raeburn  10793:     $dirRoot = $perlvar{'lonDocRoot'};
                   10794:     if (defined($getpropath)) {
                   10795:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10796:         $dirRoot =~ s/\/$//;
1.955     raeburn  10797:     } elsif (defined($getuserdir)) {
                   10798:         my $subdir=$uname.'__';
                   10799:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10800:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10801:                    ."/$udom/$subdir/$uname";
                   10802:     } elsif (defined($alternateRoot)) {
                   10803:         $dirRoot = $alternateRoot;
1.751     banghart 10804:     }
1.253     stredwic 10805: 
                   10806:     if($udom) {
                   10807:         if($uname) {
1.1135    raeburn  10808:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10809:             if ($uhome eq 'no_host') {
                   10810:                 return ([],'no_host');
                   10811:             }
1.955     raeburn  10812:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10813:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10814:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10815:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10816:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10817:             } else {
                   10818:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10819:             }
1.605     matthew  10820:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10821:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10822:                 @listing_results = split(/:/,$listing);
                   10823:             } else {
                   10824:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10825:             }
1.1135    raeburn  10826:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10827:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10828:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10829:                 return ([],$listing);
                   10830:             } else {
                   10831:                 return (\@listing_results);
1.1135    raeburn  10832:             }
1.955     raeburn  10833:         } elsif(!$alternateRoot) {
1.1136    raeburn  10834:             my (%allusers,%listerror);
1.841     albertel 10835: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10836:  	    foreach my $tryserver (keys(%servers)) {
                   10837:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10838:                                   &escape($udom),$tryserver);
                   10839:                 if ($listing eq 'unknown_cmd') {
                   10840: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10841: 				      $udom, $tryserver);
                   10842:                 } else {
                   10843:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10844:                 }
1.841     albertel 10845: 		if ($listing eq 'unknown_cmd') {
                   10846: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10847: 				      $udom, $tryserver);
                   10848: 		    @listing_results = split(/:/,$listing);
                   10849: 		} else {
                   10850: 		    @listing_results =
                   10851: 			map { &unescape($_); } split(/:/,$listing);
                   10852: 		}
1.1136    raeburn  10853:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10854:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10855:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10856:                     $listerror{$tryserver} = $listing;
                   10857:                 } else {
1.841     albertel 10858: 		    foreach my $line (@listing_results) {
                   10859: 			my ($entry) = split(/&/,$line,2);
                   10860: 			$allusers{$entry} = 1;
                   10861: 		    }
                   10862: 		}
1.253     stredwic 10863:             }
1.1136    raeburn  10864:             my @alluserslist=();
1.800     albertel 10865:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10866:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10867:             }
1.1172.2.80  raeburn  10868:             if (!%listerror) {
                   10869:                 # no errors
                   10870:                 return (\@alluserslist);
                   10871:             } elsif (scalar(keys(%servers)) == 1) {
                   10872:                 # one library server, one error
                   10873:                 my ($key) = keys(%listerror);
                   10874:                 return (\@alluserslist, $listerror{$key});
                   10875:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10876:                 # con_lost indicates that we might miss data from at least one
                   10877:                 # library server
                   10878:                 return (\@alluserslist, 'con_lost');
                   10879:             } else {
                   10880:                 # multiple library servers and no con_lost -> data should be
                   10881:                 # complete.
                   10882:                 return (\@alluserslist);
                   10883:             }
                   10884: 
1.253     stredwic 10885:         } else {
1.1136    raeburn  10886:             return ([],'missing username');
1.253     stredwic 10887:         }
1.955     raeburn  10888:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10889:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10890:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10891:         return (\@all_domains);
1.955     raeburn  10892:     } else {
1.1136    raeburn  10893:         return ([],'missing domain');
1.275     stredwic 10894:     }
                   10895: }
                   10896: 
                   10897: # --------------------------------------------- GetFileTimestamp
                   10898: # This function utilizes dirlist and returns the date stamp for
                   10899: # when it was last modified.  It will also return an error of -1
                   10900: # if an error occurs
                   10901: 
                   10902: sub GetFileTimestamp {
1.955     raeburn  10903:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10904:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10905:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10906:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10907:                                     undef,$getuserdir);
                   10908:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10909:         return -1;
                   10910:     }
                   10911:     if (ref($fileref) eq 'ARRAY') {
                   10912:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10913:         # @stats contains first the filename, then the stat output
                   10914:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10915:     } else {
                   10916:         return -1;
1.253     stredwic 10917:     }
1.26      www      10918: }
                   10919: 
1.712     albertel 10920: sub stat_file {
                   10921:     my ($uri) = @_;
1.787     albertel 10922:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10923: 
1.955     raeburn  10924:     my ($udom,$uname,$file);
1.712     albertel 10925:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10926: 	($udom,$uname,$file) =
1.811     albertel 10927: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10928: 	$file = 'userfiles/'.$file;
                   10929:     }
                   10930:     if ($uri =~ m-^/res/-) {
                   10931: 	($udom,$uname) = 
1.807     albertel 10932: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10933: 	$file = $uri;
                   10934:     }
                   10935: 
                   10936:     if (!$udom || !$uname || !$file) {
                   10937: 	# unable to handle the uri
                   10938: 	return ();
                   10939:     }
1.956     raeburn  10940:     my $getpropath;
                   10941:     if ($file =~ /^userfiles\//) {
                   10942:         $getpropath = 1;
                   10943:     }
1.1136    raeburn  10944:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10945:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10946:         return ();
                   10947:     } else {
                   10948:         if (ref($listref) eq 'ARRAY') {
                   10949:             my @stats = split('&',$listref->[0]);
                   10950: 	    shift(@stats); #filename is first
                   10951: 	    return @stats;
                   10952:         }
1.712     albertel 10953:     }
                   10954:     return ();
                   10955: }
                   10956: 
1.26      www      10957: # -------------------------------------------------------- Value of a Condition
                   10958: 
1.713     albertel 10959: # gets the value of a specific preevaluated condition
                   10960: #    stored in the string  $env{user.state.<cid>}
                   10961: # or looks up a condition reference in the bighash and if if hasn't
                   10962: # already been evaluated recurses into docondval to get the value of
                   10963: # the condition, then memoizing it to 
                   10964: #   $env{user.state.<cid>.<condition>}
1.40      www      10965: sub directcondval {
                   10966:     my $number=shift;
1.620     albertel 10967:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10968: 	&Apache::lonuserstate::evalstate();
                   10969:     }
1.713     albertel 10970:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10971: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10972:     } elsif ($number =~ /^_/) {
                   10973: 	my $sub_condition;
                   10974: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10975: 		&GDBM_READER(),0640)) {
                   10976: 	    $sub_condition=$bighash{'conditions'.$number};
                   10977: 	    untie(%bighash);
                   10978: 	}
                   10979: 	my $value = &docondval($sub_condition);
1.949     raeburn  10980: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10981: 	return $value;
                   10982:     }
1.620     albertel 10983:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10984:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10985:     } else {
                   10986:        return 2;
                   10987:     }
                   10988: }
                   10989: 
1.713     albertel 10990: # get the collection of conditions for this resource
1.26      www      10991: sub condval {
                   10992:     my $condidx=shift;
1.54      www      10993:     my $allpathcond='';
1.713     albertel 10994:     foreach my $cond (split(/\|/,$condidx)) {
                   10995: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10996: 	    $allpathcond.=
                   10997: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10998: 	}
1.191     harris41 10999:     }
1.54      www      11000:     $allpathcond=~s/\|$//;
1.713     albertel 11001:     return &docondval($allpathcond);
                   11002: }
                   11003: 
                   11004: #evaluates an expression of conditions
                   11005: sub docondval {
                   11006:     my ($allpathcond) = @_;
                   11007:     my $result=0;
                   11008:     if ($env{'request.course.id'}
                   11009: 	&& defined($allpathcond)) {
                   11010: 	my $operand='|';
                   11011: 	my @stack;
                   11012: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11013: 	    if ($chunk eq '(') {
                   11014: 		push @stack,($operand,$result);
                   11015: 	    } elsif ($chunk eq ')') {
                   11016: 		my $before=pop @stack;
                   11017: 		if (pop @stack eq '&') {
                   11018: 		    $result=$result>$before?$before:$result;
                   11019: 		} else {
                   11020: 		    $result=$result>$before?$result:$before;
                   11021: 		}
                   11022: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11023: 		$operand=$chunk;
                   11024: 	    } else {
                   11025: 		my $new=directcondval($chunk);
                   11026: 		if ($operand eq '&') {
                   11027: 		    $result=$result>$new?$new:$result;
                   11028: 		} else {
                   11029: 		    $result=$result>$new?$result:$new;
                   11030: 		}
                   11031: 	    }
                   11032: 	}
1.26      www      11033:     }
                   11034:     return $result;
1.421     albertel 11035: }
                   11036: 
                   11037: # ---------------------------------------------------- Devalidate courseresdata
                   11038: 
                   11039: sub devalidatecourseresdata {
                   11040:     my ($coursenum,$coursedomain)=@_;
                   11041:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11042:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11043: }
                   11044: 
1.763     www      11045: 
1.200     www      11046: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11047: #
                   11048: #  Parameters:
                   11049: #      $coursenum    - Number of the course.
                   11050: #      $coursedomain - Domain at which the course was created.
                   11051: #  Returns:
                   11052: #     A hash of the course parameters along (I think) with timestamps
                   11053: #     and version info.
1.877     foxr     11054: 
1.624     albertel 11055: sub get_courseresdata {
                   11056:     my ($coursenum,$coursedomain)=@_;
1.200     www      11057:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11058:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11059:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11060:     my %dumpreply;
1.417     albertel 11061:     unless (defined($cached)) {
1.624     albertel 11062: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11063: 	$result=\%dumpreply;
1.251     albertel 11064: 	my ($tmp) = keys(%dumpreply);
                   11065: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11066: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11067: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11068: 	    return $tmp;
1.416     albertel 11069: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11070: 	    $result=undef;
1.599     albertel 11071: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11072: 	}
                   11073:     }
1.624     albertel 11074:     return $result;
                   11075: }
                   11076: 
1.633     albertel 11077: sub devalidateuserresdata {
                   11078:     my ($uname,$udom)=@_;
                   11079:     my $hashid="$udom:$uname";
                   11080:     &devalidate_cache_new('userres',$hashid);
                   11081: }
                   11082: 
1.624     albertel 11083: sub get_userresdata {
                   11084:     my ($uname,$udom)=@_;
                   11085:     #most student don\'t have any data set, check if there is some data
                   11086:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11087: 
                   11088:     my $hashid="$udom:$uname";
                   11089:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11090:     if (!defined($cached)) {
                   11091: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11092: 	$result=\%resourcedata;
                   11093: 	&do_cache_new('userres',$hashid,$result,600);
                   11094:     }
                   11095:     my ($tmp)=keys(%$result);
                   11096:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11097: 	return $result;
                   11098:     }
                   11099:     #error 2 occurs when the .db doesn't exist
                   11100:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11101:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11102: 	    &logthis("<font color=\"blue\">WARNING:".
                   11103: 		     " Trying to get resource data for ".
                   11104: 		     $uname." at ".$udom.": ".
                   11105: 		     $tmp."</font>");
                   11106:         }
1.624     albertel 11107:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11108: 	#&EXT_cache_set($udom,$uname);
                   11109: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11110: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11111:     }
                   11112:     return $tmp;
                   11113: }
1.879     foxr     11114: #----------------------------------------------- resdata - return resource data
                   11115: #  Purpose:
                   11116: #    Return resource data for either users or for a course.
                   11117: #  Parameters:
                   11118: #     $name      - Course/user name.
                   11119: #     $domain    - Name of the domain the user/course is registered on.
                   11120: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11121: #     @which     - Array of names of resources desired.
                   11122: #  Returns:
                   11123: #     The value of the first reasource in @which that is found in the
                   11124: #     resource hash.
                   11125: #  Exceptional Conditions:
                   11126: #     If the $type passed in is not valid (not the string 'course' or 
                   11127: #     'user', an undefined  reference is returned.
                   11128: #     If none of the resources are found, an undef is returned
1.624     albertel 11129: sub resdata {
                   11130:     my ($name,$domain,$type,@which)=@_;
                   11131:     my $result;
                   11132:     if ($type eq 'course') {
                   11133: 	$result=&get_courseresdata($name,$domain);
                   11134:     } elsif ($type eq 'user') {
                   11135: 	$result=&get_userresdata($name,$domain);
                   11136:     }
                   11137:     if (!ref($result)) { return $result; }    
1.251     albertel 11138:     foreach my $item (@which) {
1.927     albertel 11139: 	if (defined($result->{$item->[0]})) {
                   11140: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11141: 	}
1.250     albertel 11142:     }
1.291     albertel 11143:     return undef;
1.200     www      11144: }
                   11145: 
1.1172.2.31  raeburn  11146: sub get_numsuppfiles {
                   11147:     my ($cnum,$cdom,$ignorecache)=@_;
                   11148:     my $hashid=$cnum.':'.$cdom;
                   11149:     my ($suppcount,$cached);
                   11150:     unless ($ignorecache) {
                   11151:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11152:     }
                   11153:     unless (defined($cached)) {
                   11154:         my $chome=&homeserver($cnum,$cdom);
                   11155:         unless ($chome eq 'no_host') {
                   11156:             ($suppcount,my $errors) = (0,0);
                   11157:             my $suppmap = 'supplemental.sequence';
                   11158:             ($suppcount,$errors) =
                   11159:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11160:         }
                   11161:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11162:     }
                   11163:     return $suppcount;
                   11164: }
                   11165: 
1.379     matthew  11166: #
                   11167: # EXT resource caching routines
                   11168: #
                   11169: 
                   11170: sub clear_EXT_cache_status {
1.383     albertel 11171:     &delenv('cache.EXT.');
1.379     matthew  11172: }
                   11173: 
                   11174: sub EXT_cache_status {
                   11175:     my ($target_domain,$target_user) = @_;
1.383     albertel 11176:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11177:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11178:         # We know already the user has no data
                   11179:         return 1;
                   11180:     } else {
                   11181:         return 0;
                   11182:     }
                   11183: }
                   11184: 
                   11185: sub EXT_cache_set {
                   11186:     my ($target_domain,$target_user) = @_;
1.383     albertel 11187:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11188:     #&appenv({$cachename => time});
1.379     matthew  11189: }
                   11190: 
1.28      www      11191: # --------------------------------------------------------- Value of a Variable
1.58      www      11192: sub EXT {
1.715     albertel 11193: 
1.1172.2.28  raeburn  11194:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11195:     unless ($varname) { return ''; }
1.218     albertel 11196:     #get real user name/domain, courseid and symb
                   11197:     my $courseid;
1.359     albertel 11198:     my $publicuser;
1.427     www      11199:     if ($symbparm) {
                   11200: 	$symbparm=&get_symb_from_alias($symbparm);
                   11201:     }
1.218     albertel 11202:     if (!($uname && $udom)) {
1.790     albertel 11203:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11204:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11205:     } else {
1.620     albertel 11206: 	$courseid=$env{'request.course.id'};
1.218     albertel 11207:     }
1.48      www      11208:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11209:     my $rest;
1.320     albertel 11210:     if (defined($therest[0])) {
1.48      www      11211:        $rest=join('.',@therest);
                   11212:     } else {
                   11213:        $rest='';
                   11214:     }
1.320     albertel 11215: 
1.57      www      11216:     my $qualifierrest=$qualifier;
                   11217:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11218:     my $spacequalifierrest=$space;
                   11219:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11220:     if ($realm eq 'user') {
1.48      www      11221: # --------------------------------------------------------------- user.resource
                   11222: 	if ($space eq 'resource') {
1.651     albertel 11223: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11224: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11225: 		 &&
1.744     albertel 11226: 		 ($symbparm eq &symbread()) ) {	
                   11227: 		# if we are in the middle of processing the resource the
                   11228: 		# get the value we are planning on committing
                   11229:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11230:                     return $Apache::lonhomework::results{$qualifierrest};
                   11231:                 } else {
                   11232:                     return $Apache::lonhomework::history{$qualifierrest};
                   11233:                 }
1.335     albertel 11234: 	    } else {
1.359     albertel 11235: 		my %restored;
1.620     albertel 11236: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11237: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11238: 		} else {
                   11239: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11240: 		}
1.335     albertel 11241: 		return $restored{$qualifierrest};
                   11242: 	    }
1.48      www      11243: # ----------------------------------------------------------------- user.access
                   11244:         } elsif ($space eq 'access') {
1.218     albertel 11245: 	    # FIXME - not supporting calls for a specific user
1.48      www      11246:             return &allowed($qualifier,$rest);
                   11247: # ------------------------------------------ user.preferences, user.environment
                   11248:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11249: 	    if (($uname eq $env{'user.name'}) &&
                   11250: 		($udom eq $env{'user.domain'})) {
                   11251: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11252: 	    } else {
1.359     albertel 11253: 		my %returnhash;
                   11254: 		if (!$publicuser) {
                   11255: 		    %returnhash=&userenvironment($udom,$uname,
                   11256: 						 $qualifierrest);
                   11257: 		}
1.218     albertel 11258: 		return $returnhash{$qualifierrest};
                   11259: 	    }
1.48      www      11260: # ----------------------------------------------------------------- user.course
                   11261:         } elsif ($space eq 'course') {
1.218     albertel 11262: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11263:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11264: # ------------------------------------------------------------------- user.role
                   11265:         } elsif ($space eq 'role') {
1.218     albertel 11266: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11267:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11268:             if ($qualifier eq 'value') {
                   11269: 		return $role;
                   11270:             } elsif ($qualifier eq 'extent') {
                   11271:                 return $where;
                   11272:             }
                   11273: # ----------------------------------------------------------------- user.domain
                   11274:         } elsif ($space eq 'domain') {
1.218     albertel 11275:             return $udom;
1.48      www      11276: # ------------------------------------------------------------------- user.name
                   11277:         } elsif ($space eq 'name') {
1.218     albertel 11278:             return $uname;
1.48      www      11279: # ---------------------------------------------------- Any other user namespace
1.29      www      11280:         } else {
1.359     albertel 11281: 	    my %reply;
                   11282: 	    if (!$publicuser) {
                   11283: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11284: 	    }
                   11285: 	    return $reply{$qualifierrest};
1.48      www      11286:         }
1.236     www      11287:     } elsif ($realm eq 'query') {
                   11288: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11289:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11290: 						[$spacequalifierrest]);
1.620     albertel 11291: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11292:    } elsif ($realm eq 'request') {
1.48      www      11293: # ------------------------------------------------------------- request.browser
                   11294:         if ($space eq 'browser') {
1.1145    bisitz   11295:             return $env{'browser.'.$qualifier};
1.57      www      11296: # ------------------------------------------------------------ request.filename
                   11297:         } else {
1.620     albertel 11298:             return $env{'request.'.$spacequalifierrest};
1.29      www      11299:         }
1.28      www      11300:     } elsif ($realm eq 'course') {
1.48      www      11301: # ---------------------------------------------------------- course.description
1.620     albertel 11302:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11303:     } elsif ($realm eq 'resource') {
1.165     www      11304: 
1.620     albertel 11305: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11306: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11307: 	}
1.693     albertel 11308: 
1.1172.2.30  raeburn  11309:         if ($qualifier eq '') {
                   11310: 	    if ($space eq 'title') {
                   11311: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11312: 	        return &gettitle($symbparm);
                   11313: 	    }
1.693     albertel 11314: 	
1.1172.2.30  raeburn  11315: 	    if ($space eq 'map') {
                   11316: 	        my ($map) = &decode_symb($symbparm);
                   11317: 	        return &symbread($map);
                   11318: 	    }
                   11319:             if ($space eq 'maptitle') {
                   11320:                 my ($map) = &decode_symb($symbparm);
                   11321:                 return &gettitle($map);
                   11322:             }
                   11323: 	    if ($space eq 'filename') {
                   11324: 	        if ($symbparm) {
                   11325: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11326: 	        }
                   11327: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11328: 	    }
1.1172.2.30  raeburn  11329: 
                   11330:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11331:                 if ($space eq 'visibleparts') {
                   11332:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11333:                     my $item;
                   11334:                     if (ref($navmap)) {
                   11335:                         my $res = $navmap->getBySymb($symbparm);
                   11336:                         my $parts = $res->parts();
                   11337:                         if (ref($parts) eq 'ARRAY') {
                   11338:                             $item = join(',',@{$parts});
                   11339:                         }
                   11340:                         undef($navmap);
                   11341:                     }
                   11342:                     return $item;
                   11343:                 }
                   11344:             }
                   11345:         }
1.693     albertel 11346: 
                   11347: 	my ($section, $group, @groups);
1.593     albertel 11348: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11349:         if (($courseid eq '') && ($cid)) {
                   11350:             $courseid = $cid;
                   11351:         }
                   11352: 	if (($symbparm && $courseid) && 
                   11353: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11354: 
1.218     albertel 11355: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11356: 
1.60      www      11357: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11358: 	    my $symbp=$symbparm;
1.735     albertel 11359: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11360: 
                   11361: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11362: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11363: 
1.620     albertel 11364: 	    if (($env{'user.name'} eq $uname) &&
                   11365: 		($env{'user.domain'} eq $udom)) {
                   11366: 		$section=$env{'request.course.sec'};
1.733     raeburn  11367:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11368:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11369: 	    } else {
1.539     albertel 11370: 		if (! defined($usection)) {
1.551     albertel 11371: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11372: 		} else {
                   11373: 		    $section = $usection;
                   11374: 		}
1.733     raeburn  11375:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11376: 	    }
                   11377: 
                   11378: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11379: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11380: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11381: 
1.593     albertel 11382: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11383: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11384: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11385: 
1.60      www      11386: # ----------------------------------------------------------- first, check user
1.624     albertel 11387: 
                   11388: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11389: 				       ([$courselevelr,'resource'],
                   11390: 					[$courselevelm,'map'     ],
                   11391: 					[$courselevel, 'course'  ]));
1.931     albertel 11392: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11393: 
1.594     albertel 11394: # ------------------------------------------------ second, check some of course
1.684     raeburn  11395:             my $coursereply;
1.691     raeburn  11396:             if (@groups > 0) {
                   11397:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11398:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11399:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11400:             }
1.96      www      11401: 
1.684     raeburn  11402: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11403: 				  $env{'course.'.$courseid.'.domain'},
                   11404: 				  'course',
                   11405: 				  ([$seclevelr,   'resource'],
                   11406: 				   [$seclevelm,   'map'     ],
                   11407: 				   [$seclevel,    'course'  ],
                   11408: 				   [$courselevelr,'resource']));
                   11409: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11410: 
1.60      www      11411: # ------------------------------------------------------ third, check map parms
1.218     albertel 11412: 	    my %parmhash=();
                   11413: 	    my $thisparm='';
                   11414: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11415: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11416: 		    &GDBM_READER(),0640)) {
1.218     albertel 11417: 		$thisparm=$parmhash{$symbparm};
                   11418: 		untie(%parmhash);
                   11419: 	    }
1.927     albertel 11420: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11421: 	}
1.594     albertel 11422: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11423: 
1.218     albertel 11424: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11425: 	my $filename;
                   11426: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11427: 	if ($symbparm) {
1.409     www      11428: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11429: 	} else {
1.620     albertel 11430: 	    $filename=$env{'request.filename'};
1.282     albertel 11431: 	}
                   11432: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11433: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11434: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11435: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11436: 
1.927     albertel 11437: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11438: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11439: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11440: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11441: 				     $env{'course.'.$courseid.'.domain'},
                   11442: 				     'course',
1.927     albertel 11443: 				     ([$courselevelm,'map'   ],
                   11444: 				      [$courselevel, 'course']));
                   11445: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11446: 	}
1.145     www      11447: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11448: 	unless ($space eq '0') {
1.336     albertel 11449: 	    my @parts=split(/_/,$space);
                   11450: 	    my $id=pop(@parts);
                   11451: 	    my $part=join('_',@parts);
                   11452: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11453: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11454: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11455: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11456: 	}
1.395     albertel 11457: 	if ($recurse) { return undef; }
                   11458: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11459: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11460: # ---------------------------------------------------- Any other user namespace
                   11461:     } elsif ($realm eq 'environment') {
                   11462: # ----------------------------------------------------------------- environment
1.620     albertel 11463: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11464: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11465: 	} else {
1.770     albertel 11466: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11467: 		return '';
                   11468: 	    }
1.219     albertel 11469: 	    my %returnhash=&userenvironment($udom,$uname,
                   11470: 					    $spacequalifierrest);
                   11471: 	    return $returnhash{$spacequalifierrest};
                   11472: 	}
1.28      www      11473:     } elsif ($realm eq 'system') {
1.48      www      11474: # ----------------------------------------------------------------- system.time
                   11475: 	if ($space eq 'time') {
                   11476: 	    return time;
                   11477:         }
1.696     albertel 11478:     } elsif ($realm eq 'server') {
                   11479: # ----------------------------------------------------------------- system.time
                   11480: 	if ($space eq 'name') {
                   11481: 	    return $ENV{'SERVER_NAME'};
                   11482:         }
1.28      www      11483:     }
1.48      www      11484:     return '';
1.61      www      11485: }
                   11486: 
1.927     albertel 11487: sub get_reply {
                   11488:     my ($reply_value) = @_;
1.940     raeburn  11489:     if (ref($reply_value) eq 'ARRAY') {
                   11490:         if (wantarray) {
                   11491: 	    return @$reply_value;
                   11492:         }
                   11493:         return $reply_value->[0];
                   11494:     } else {
                   11495:         return $reply_value;
1.927     albertel 11496:     }
                   11497: }
                   11498: 
1.691     raeburn  11499: sub check_group_parms {
                   11500:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11501:     my @groupitems = ();
                   11502:     my $resultitem;
1.927     albertel 11503:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11504:     foreach my $group (@{$groups}) {
                   11505:         foreach my $level (@levels) {
1.927     albertel 11506:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11507:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11508:         }
                   11509:     }
                   11510:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11511:                             $env{'course.'.$courseid.'.domain'},
                   11512:                                      'course',@groupitems);
                   11513:     return $coursereply;
                   11514: }
                   11515: 
                   11516: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11517:     my ($courseid,@groups) = @_;
                   11518:     @groups = sort(@groups);
1.691     raeburn  11519:     return @groups;
                   11520: }
                   11521: 
1.395     albertel 11522: sub packages_tab_default {
                   11523:     my ($uri,$varname)=@_;
                   11524:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11525: 
                   11526:     my (@extension,@specifics,$do_default);
                   11527:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11528: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11529: 	if ($pack_type eq 'default') {
                   11530: 	    $do_default=1;
                   11531: 	} elsif ($pack_type eq 'extension') {
                   11532: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11533: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11534: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11535: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11536: 	}
                   11537:     }
                   11538:     # first look for a package that matches the requested part id
                   11539:     foreach my $package (@specifics) {
                   11540: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11541: 	next if ($pack_part ne $part);
                   11542: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11543: 	    return $packagetab{"$pack_type&$name&default"};
                   11544: 	}
                   11545:     }
                   11546:     # look for any possible matching non extension_ package
                   11547:     foreach my $package (@specifics) {
                   11548: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11549: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11550: 	    return $packagetab{"$pack_type&$name&default"};
                   11551: 	}
1.585     albertel 11552: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11553: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11554: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11555: 	}
                   11556:     }
1.738     albertel 11557:     # look for any posible extension_ match
                   11558:     foreach my $package (@extension) {
                   11559: 	my ($package,$pack_type)=@{$package};
                   11560: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11561: 	    return $packagetab{"$pack_type&$name&default"};
                   11562: 	}
                   11563: 	if (defined($packagetab{$package."&$name&default"})) {
                   11564: 	    return $packagetab{$package."&$name&default"};
                   11565: 	}
                   11566:     }
                   11567:     # look for a global default setting
                   11568:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11569: 	return $packagetab{"default&$name&default"};
                   11570:     }
1.395     albertel 11571:     return undef;
                   11572: }
                   11573: 
1.334     albertel 11574: sub add_prefix_and_part {
                   11575:     my ($prefix,$part)=@_;
                   11576:     my $keyroot;
                   11577:     if (defined($prefix) && $prefix !~ /^__/) {
                   11578: 	# prefix that has a part already
                   11579: 	$keyroot=$prefix;
                   11580:     } elsif (defined($prefix)) {
                   11581: 	# prefix that is missing a part
                   11582: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11583:     } else {
                   11584: 	# no prefix at all
                   11585: 	if (defined($part)) { $keyroot='_'.$part; }
                   11586:     }
                   11587:     return $keyroot;
                   11588: }
                   11589: 
1.71      www      11590: # ---------------------------------------------------------------- Get metadata
                   11591: 
1.599     albertel 11592: my %metaentry;
1.1070    www      11593: my %importedpartids;
1.1172.2.99  raeburn  11594: my %importedrespids;
1.71      www      11595: sub metadata {
1.176     www      11596:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11597:     $uri=&declutter($uri);
1.288     albertel 11598:     # if it is a non metadata possible uri return quickly
1.529     albertel 11599:     if (($uri eq '') || 
                   11600: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11601: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11602:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11603: 	return undef;
                   11604:     }
1.1172.2.49  raeburn  11605:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11606: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11607: 	return undef;
1.288     albertel 11608:     }
1.73      www      11609:     my $filename=$uri;
                   11610:     $uri=~s/\.meta$//;
1.172     www      11611: #
                   11612: # Is the metadata already cached?
1.177     www      11613: # Look at timestamp of caching
1.172     www      11614: # Everything is cached by the main uri, libraries are never directly cached
                   11615: #
1.428     albertel 11616:     if (!defined($liburi)) {
1.599     albertel 11617: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11618: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11619:     }
                   11620:     {
1.1069    www      11621: # Imported parts would go here
1.1172.2.99  raeburn  11622:         my @origfiletagids=();
1.1069    www      11623:         my $importedparts=0;
1.1172.2.99  raeburn  11624: 
                   11625: # Imported responseids would go here
                   11626:         my $importedresponses=0;
1.172     www      11627: #
                   11628: # Is this a recursive call for a library?
                   11629: #
1.599     albertel 11630: #	if (! exists($metacache{$uri})) {
                   11631: #	    $metacache{$uri}={};
                   11632: #	}
1.924     albertel 11633: 	my $cachetime = 60*60;
1.171     www      11634:         if ($liburi) {
                   11635: 	    $liburi=&declutter($liburi);
                   11636:             $filename=$liburi;
1.401     bowersj2 11637:         } else {
1.599     albertel 11638: 	    &devalidate_cache_new('meta',$uri);
                   11639: 	    undef(%metaentry);
1.401     bowersj2 11640: 	}
1.140     www      11641:         my %metathesekeys=();
1.73      www      11642:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11643: 	my $metastring;
1.1140    www      11644: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11645: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11646: 	    $metastring = 
1.929     albertel 11647: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11648: 					  ('grade_target' => 'meta'));
                   11649: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11650: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11651:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11652: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11653: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11654: 	    $metastring=&getfile($file);
1.489     albertel 11655: 	}
1.208     albertel 11656:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11657:         my $token;
1.140     www      11658:         undef %metathesekeys;
1.71      www      11659:         while ($token=$parser->get_token) {
1.339     albertel 11660: 	    if ($token->[0] eq 'S') {
                   11661: 		if (defined($token->[2]->{'package'})) {
1.172     www      11662: #
                   11663: # This is a package - get package info
                   11664: #
1.339     albertel 11665: 		    my $package=$token->[2]->{'package'};
                   11666: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11667: 		    if (defined($token->[2]->{'id'})) { 
                   11668: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11669: 		    }
1.599     albertel 11670: 		    if ($metaentry{':packages'}) {
                   11671: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11672: 		    } else {
1.599     albertel 11673: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11674: 		    }
1.736     albertel 11675: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11676: 			my $part=$keyroot;
                   11677: 			$part=~s/^\_//;
1.736     albertel 11678: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11679: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11680: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11681: 			    # ignore package.tab specified default values
                   11682:                             # here &package_tab_default() will fetch those
                   11683: 			    if ($subp eq 'default') { next; }
1.736     albertel 11684: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11685: 			    my $unikey;
                   11686: 			    if ($pack =~ /_0$/) {
                   11687: 				$unikey='parameter_0_'.$name;
                   11688: 				$part=0;
                   11689: 			    } else {
                   11690: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11691: 			    }
1.339     albertel 11692: 			    if ($subp eq 'display') {
                   11693: 				$value.=' [Part: '.$part.']';
                   11694: 			    }
1.599     albertel 11695: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11696: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11697: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11698: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11699: 			    }
1.599     albertel 11700: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11701: 				$metaentry{':'.$unikey}=
                   11702: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11703: 			    }
1.339     albertel 11704: 			}
                   11705: 		    }
                   11706: 		} else {
1.172     www      11707: #
                   11708: # This is not a package - some other kind of start tag
1.339     albertel 11709: #
                   11710: 		    my $entry=$token->[1];
1.1068    www      11711: 		    my $unikey='';
1.175     www      11712: 
1.339     albertel 11713: 		    if ($entry eq 'import') {
1.175     www      11714: #
                   11715: # Importing a library here
1.339     albertel 11716: #
1.1067    www      11717:                         my $location=$parser->get_text('/import');
                   11718:                         my $dir=$filename;
                   11719:                         $dir=~s|[^/]*$||;
                   11720:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11721: 
                   11722:                         my $importid=$token->[2]->{'id'};
1.1068    www      11723:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11724: #
                   11725: # Check metadata for imported file to
                   11726: # see if it contained response items
                   11727: #
                   11728:                         my %currmetaentry = %metaentry;
                   11729:                         my $libresponseorder = &metadata($location,'responseorder');
                   11730:                         my $origfile;
                   11731:                         if ($libresponseorder ne '') {
                   11732:                             if ($#origfiletagids<0) {
                   11733:                                 undef(%importedrespids);
                   11734:                                 undef(%importedpartids);
                   11735:                             }
                   11736:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11737:                             if (@{$importedrespids{$importid}} > 0) {
                   11738:                                 $importedresponses = 1;
                   11739: # We need to get the original file and the imported file to get the response order correct
                   11740: # Load and inspect original file
                   11741:                                 if ($#origfiletagids<0) {
                   11742:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11743:                                     $origfile=&getfile($origfilelocation);
                   11744:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11745:                                 }
                   11746:                             }
                   11747:                         }
                   11748: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11749: # hash populated for imported library file
                   11750:                         %metaentry = %currmetaentry;
                   11751:                         undef(%currmetaentry);
1.1068    www      11752:                         if ($importmode eq 'problem') {
1.1069    www      11753: # Import as problem/response
1.1068    www      11754:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11755:                         } elsif ($importmode eq 'part') {
                   11756: # Import as part(s)
1.1069    www      11757:                            $importedparts=1;
                   11758: # We need to get the original file and the imported file to get the part order correct
                   11759: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11760: # Load and inspect original file if we didn't do that already
                   11761:                            if ($#origfiletagids<0) {
                   11762:                                undef(%importedrespids);
                   11763:                                undef(%importedpartids);
                   11764:                                if ($origfile eq '') {
                   11765:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11766:                                    $origfile=&getfile($origfilelocation);
                   11767:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11768:                                }
1.1070    www      11769:                            }
                   11770: 
1.1069    www      11771: # Load and inspect imported file
                   11772:                            my $impfile=&getfile($location);
                   11773:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11774:                            if ($#impfilepartids>=0) {
                   11775: # This problem had parts
1.1070    www      11776:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11777:                            } else {
                   11778: # Importing by turning a single problem into a problem part
                   11779: # It gets the import-tags ID as part-ID
                   11780:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11781:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11782:                            }
1.1068    www      11783:                         } else {
                   11784: # Normal import
                   11785:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11786:                            if (defined($token->[2]->{'id'})) {
                   11787:                               $unikey.='_'.$token->[2]->{'id'};
                   11788:                            }
1.1067    www      11789:                         }
                   11790: 
1.339     albertel 11791: 			if ($depthcount<20) {
1.736     albertel 11792: 			    my $metadata = 
                   11793: 				&metadata($uri,'keys', $location,$unikey,
                   11794: 					  $depthcount+1);
                   11795: 			    foreach my $meta (split(',',$metadata)) {
                   11796: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11797: 				$metathesekeys{$meta}=1;
1.339     albertel 11798: 			    }
1.1068    www      11799: 			
                   11800:                         }
1.1067    www      11801: 		    } else {
                   11802: #
                   11803: # Not importing, some other kind of non-package, non-library start tag
                   11804: # 
                   11805:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11806:                         if (defined($token->[2]->{'id'})) {
                   11807:                             $unikey.='_'.$token->[2]->{'id'};
                   11808:                         }
1.339     albertel 11809: 			if (defined($token->[2]->{'name'})) { 
                   11810: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11811: 			}
                   11812: 			$metathesekeys{$unikey}=1;
1.736     albertel 11813: 			foreach my $param (@{$token->[3]}) {
                   11814: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11815: 				$token->[2]->{$param};
1.339     albertel 11816: 			}
                   11817: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11818: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11819: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11820: 		 # only ws inside the tag, and not in default, so use default
                   11821: 		 # as value
1.599     albertel 11822: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11823: 			} elsif ( $internaltext =~ /\S/ ) {
                   11824: 		  # something interesting inside the tag
                   11825: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11826: 			} else {
1.908     albertel 11827: 		  # no interesting values, don't set a default
1.339     albertel 11828: 			}
1.172     www      11829: # end of not-a-package not-a-library import
1.339     albertel 11830: 		    }
1.172     www      11831: # end of not-a-package start tag
1.339     albertel 11832: 		}
1.172     www      11833: # the next is the end of "start tag"
1.339     albertel 11834: 	    }
                   11835: 	}
1.483     albertel 11836: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11837: 	$extension = lc($extension);
                   11838: 	if ($extension eq 'htm') { $extension='html'; }
                   11839: 
1.737     albertel 11840: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11841: 	    #no specific packages #how's our extension
                   11842: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11843: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11844: 					 \%metathesekeys);
                   11845: 	}
1.883     albertel 11846: 
                   11847: 	if (!exists($metaentry{':packages'})
                   11848: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11849: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11850: 		#no specific packages well let's get default then
                   11851: 		if ($key!~/^default&/) { next; }
1.488     albertel 11852: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11853: 					     \%metathesekeys);
                   11854: 	    }
                   11855: 	}
1.338     www      11856: # are there custom rights to evaluate
1.599     albertel 11857: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11858: 
1.338     www      11859:     #
                   11860:     # Importing a rights file here
1.339     albertel 11861:     #
                   11862: 	    unless ($depthcount) {
1.599     albertel 11863: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11864: 		my $dir=$filename;
                   11865: 		$dir=~s|[^/]*$||;
                   11866: 		$location=&filelocation($dir,$location);
1.736     albertel 11867: 		my $rights_metadata =
                   11868: 		    &metadata($uri,'keys',$location,'_rights',
                   11869: 			      $depthcount+1);
                   11870: 		foreach my $rights (split(',',$rights_metadata)) {
                   11871: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11872: 		    $metathesekeys{$rights}=1;
1.339     albertel 11873: 		}
                   11874: 	    }
                   11875: 	}
1.737     albertel 11876: 	# uniqifiy package listing
                   11877: 	my %seen;
                   11878: 	my @uniq_packages =
                   11879: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11880: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11881: 
1.1172.2.99  raeburn  11882:         if (($importedresponses) || ($importedparts)) {
                   11883:             if ($importedparts) {
1.1070    www      11884: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11885:                 $metaentry{':partorder'}='';
                   11886:                 $metathesekeys{'partorder'}=1;
                   11887:             }
                   11888:             if ($importedresponses) {
                   11889: # We had imported responses and need to rebuild responseorder
                   11890:                 $metaentry{':responseorder'}='';
                   11891:                 $metathesekeys{'responseorder'}=1;
                   11892:             }
                   11893:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11894:                 my $origid = $origfiletagids[$index+1];
                   11895:                 if ($origfiletagids[$index] eq 'part') {
                   11896: # Original part, part of the problem
                   11897:                     if ($importedparts) {
                   11898:                         $metaentry{':partorder'}.=','.$origid;
                   11899:                     }
                   11900:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11901:                     if ($importedparts) {
                   11902: # We have imported parts at this position
                   11903:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11904:                     }
                   11905:                     if ($importedresponses) {
                   11906: # We have imported responses at this position
                   11907:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11908:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11909:                         }
                   11910:                     }
                   11911:                 } else {
                   11912: # Original response item, part of the problem
                   11913:                     if ($importedresponses) {
                   11914:                         $metaentry{':responseorder'}.=','.$origid;
                   11915:                     }
                   11916:                 }
                   11917:             }
                   11918:             if ($importedparts) {
                   11919:                 $metaentry{':partorder'}=~s/^\,//;
                   11920:             }
                   11921:             if ($importedresponses) {
                   11922:                 $metaentry{':responseorder'}=~s/^\,//;
                   11923:             }
1.1070    www      11924:         }
                   11925: 
1.737     albertel 11926: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11927: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11928: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11929: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11930: # this is the end of "was not already recently cached
1.71      www      11931:     }
1.599     albertel 11932:     return $metaentry{':'.$what};
1.261     albertel 11933: }
                   11934: 
1.488     albertel 11935: sub metadata_create_package_def {
1.483     albertel 11936:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11937:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11938:     if ($subp eq 'default') { next; }
                   11939:     
1.599     albertel 11940:     if (defined($metaentry{':packages'})) {
                   11941: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11942:     } else {
1.599     albertel 11943: 	$metaentry{':packages'}=$package;
1.483     albertel 11944:     }
                   11945:     my $value=$packagetab{$key};
                   11946:     my $unikey;
                   11947:     $unikey='parameter_0_'.$name;
1.599     albertel 11948:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11949:     $$metathesekeys{$unikey}=1;
1.599     albertel 11950:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11951: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11952:     }
1.599     albertel 11953:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11954: 	$metaentry{':'.$unikey}=
                   11955: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11956:     }
                   11957: }
                   11958: 
1.261     albertel 11959: sub metadata_generate_part0 {
                   11960:     my ($metadata,$metacache,$uri) = @_;
                   11961:     my %allnames;
1.737     albertel 11962:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11963: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11964: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11965: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11966: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11967: 	    $allnames{$name}=$part;
                   11968: 	  }
                   11969: 	}
                   11970:     }
                   11971:     foreach my $name (keys(%allnames)) {
                   11972:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11973:       my $key=":parameter_0_$name";
1.261     albertel 11974:       $$metacache{"$key.part"}='0';
                   11975:       $$metacache{"$key.name"}=$name;
1.428     albertel 11976:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11977: 					   $allnames{$name}.'_'.$name.
                   11978: 					   '.type'};
1.428     albertel 11979:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11980: 			     '.display'};
1.644     www      11981:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11982:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11983:       $$metacache{"$key.display"}=$olddis;
                   11984:     }
1.71      www      11985: }
                   11986: 
1.764     albertel 11987: # ------------------------------------------------------ Devalidate title cache
                   11988: 
                   11989: sub devalidate_title_cache {
                   11990:     my ($url)=@_;
                   11991:     if (!$env{'request.course.id'}) { return; }
                   11992:     my $symb=&symbread($url);
                   11993:     if (!$symb) { return; }
                   11994:     my $key=$env{'request.course.id'}."\0".$symb;
                   11995:     &devalidate_cache_new('title',$key);
                   11996: }
                   11997: 
1.1014    droeschl 11998: # ------------------------------------------------- Get the title of a course
                   11999: 
                   12000: sub current_course_title {
                   12001:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12002: }
1.301     www      12003: # ------------------------------------------------- Get the title of a resource
                   12004: 
                   12005: sub gettitle {
                   12006:     my $urlsymb=shift;
                   12007:     my $symb=&symbread($urlsymb);
1.534     albertel 12008:     if ($symb) {
1.620     albertel 12009: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12010: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12011: 	if (defined($cached)) { 
                   12012: 	    return $result;
                   12013: 	}
1.534     albertel 12014: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12015: 	my $title='';
1.907     albertel 12016: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12017: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12018: 	} else {
                   12019: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12020: 		    &GDBM_READER(),0640)) {
                   12021: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12022: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12023: 		untie(%bighash);
                   12024: 	    }
1.534     albertel 12025: 	}
                   12026: 	$title=~s/\&colon\;/\:/gs;
                   12027: 	if ($title) {
1.1159    www      12028: # Remember both $symb and $title for dynamic metadata
                   12029:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12030:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12031: # Cache this title and then return it
1.599     albertel 12032: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12033: 	}
                   12034: 	$urlsymb=$url;
                   12035:     }
                   12036:     my $title=&metadata($urlsymb,'title');
                   12037:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12038:     return $title;
1.301     www      12039: }
1.613     albertel 12040: 
1.614     albertel 12041: sub get_slot {
                   12042:     my ($which,$cnum,$cdom)=@_;
                   12043:     if (!$cnum || !$cdom) {
1.790     albertel 12044: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12045: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12046: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12047:     }
1.703     albertel 12048:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12049:     my %slotinfo;
                   12050:     if (exists($remembered{$key})) {
                   12051: 	$slotinfo{$which} = $remembered{$key};
                   12052:     } else {
                   12053: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12054: 	&Apache::lonhomework::showhash(%slotinfo);
                   12055: 	my ($tmp)=keys(%slotinfo);
                   12056: 	if ($tmp=~/^error:/) { return (); }
                   12057: 	$remembered{$key} = $slotinfo{$which};
                   12058:     }
1.616     albertel 12059:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12060: 	return %{$slotinfo{$which}};
                   12061:     }
                   12062:     return $slotinfo{$which};
1.614     albertel 12063: }
1.1150    raeburn  12064: 
                   12065: sub get_reservable_slots {
                   12066:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12067:     my $now = time;
                   12068:     my $reservable_info;
                   12069:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12070:     if (exists($remembered{$key})) {
                   12071:         $reservable_info = $remembered{$key};
                   12072:     } else {
                   12073:         my %resv;
                   12074:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12075:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12076:         $reservable_info = \%resv;
                   12077:         $remembered{$key} = $reservable_info;
                   12078:     }
                   12079:     return $reservable_info;
                   12080: }
                   12081: 
                   12082: sub get_course_slots {
                   12083:     my ($cnum,$cdom) = @_;
                   12084:     my $hashid=$cnum.':'.$cdom;
                   12085:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12086:     if (defined($cached)) {
                   12087:         if (ref($result) eq 'HASH') {
                   12088:             return %{$result};
                   12089:         }
                   12090:     } else {
                   12091:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12092:         my ($tmp) = keys(%slots);
                   12093:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12094:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12095:             return %slots;
                   12096:         }
                   12097:     }
                   12098:     return;
                   12099: }
                   12100: 
                   12101: sub devalidate_slots_cache {
                   12102:     my ($cnum,$cdom)=@_;
                   12103:     my $hashid=$cnum.':'.$cdom;
                   12104:     &devalidate_cache_new('allslots',$hashid);
                   12105: }
                   12106: 
1.1172.2.8  raeburn  12107: sub get_coursechange {
                   12108:     my ($cdom,$cnum) = @_;
                   12109:     if ($cdom eq '' || $cnum eq '') {
                   12110:         return unless ($env{'request.course.id'});
                   12111:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12112:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12113:     }
                   12114:     my $hashid=$cdom.'_'.$cnum;
                   12115:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12116:     if ((defined($cached)) && ($change ne '')) {
                   12117:         return $change;
                   12118:     } else {
                   12119:         my %crshash;
                   12120:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12121:         if ($crshash{'internal.contentchange'} eq '') {
                   12122:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12123:             if ($change eq '') {
                   12124:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12125:                 $change = $crshash{'internal.created'};
                   12126:             }
                   12127:         } else {
                   12128:             $change = $crshash{'internal.contentchange'};
                   12129:         }
                   12130:         my $cachetime = 600;
                   12131:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12132:     }
                   12133:     return $change;
                   12134: }
                   12135: 
                   12136: sub devalidate_coursechange_cache {
                   12137:     my ($cnum,$cdom)=@_;
                   12138:     my $hashid=$cnum.':'.$cdom;
                   12139:     &devalidate_cache_new('crschange',$hashid);
                   12140: }
                   12141: 
1.31      www      12142: # ------------------------------------------------- Update symbolic store links
                   12143: 
                   12144: sub symblist {
                   12145:     my ($mapname,%newhash)=@_;
1.438     www      12146:     $mapname=&deversion(&declutter($mapname));
1.31      www      12147:     my %hash;
1.620     albertel 12148:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12149:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12150:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12151: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12152: 		next if ($url eq 'last_known'
                   12153: 			 && $env{'form.no_update_last_known'});
                   12154: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12155: 						    $newhash{$url}->[1],
                   12156: 						    $newhash{$url}->[0]);
1.191     harris41 12157:             }
1.31      www      12158:             if (untie(%hash)) {
                   12159: 		return 'ok';
                   12160:             }
                   12161:         }
                   12162:     }
                   12163:     return 'error';
1.212     www      12164: }
                   12165: 
                   12166: # --------------------------------------------------------------- Verify a symb
                   12167: 
                   12168: sub symbverify {
1.1172.2.11  raeburn  12169:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12170:     my $thisfn=$thisurl;
1.439     www      12171:     $thisfn=&declutter($thisfn);
1.215     www      12172: # direct jump to resource in page or to a sequence - will construct own symbs
                   12173:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12174: # check URL part
1.409     www      12175:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12176: 
1.431     www      12177:     unless ($url eq $thisfn) { return 0; }
1.213     www      12178: 
1.216     www      12179:     $symb=&symbclean($symb);
1.510     www      12180:     $thisurl=&deversion($thisurl);
1.439     www      12181:     $thisfn=&deversion($thisfn);
1.213     www      12182: 
                   12183:     my %bighash;
                   12184:     my $okay=0;
1.431     www      12185: 
1.620     albertel 12186:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12187:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  12188:         my $noclutter;
1.1032    raeburn  12189:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12190:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12191:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12192:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12193:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12194:                 $noclutter = 1;
                   12195:             }
                   12196:         }
                   12197:         my $ids;
                   12198:         if ($noclutter) {
                   12199:             $ids=$bighash{'ids_'.$thisurl};
                   12200:         } else {
                   12201:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12202:         }
1.1102    raeburn  12203:         unless ($ids) {
1.1172.2.13  raeburn  12204:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12205:             $ids=$bighash{$idkey};
1.216     www      12206:         }
                   12207:         if ($ids) {
                   12208: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12209:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12210:                 $symb =~ s/\?.+$//;
                   12211:             }
1.800     albertel 12212: 	    foreach my $id (split(/\,/,$ids)) {
                   12213: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12214:                if (
                   12215:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12216:    eq $symb) {
1.1172.2.11  raeburn  12217:                    if (ref($encstate)) {
                   12218:                        $$encstate = $bighash{'encrypted_'.$id};
                   12219:                    }
1.1172.2.13  raeburn  12220:                    if (($env{'request.role.adv'}) ||
                   12221:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12222:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12223:                        $okay=1;
                   12224:                        last;
                   12225:                    }
                   12226:                }
                   12227:            }
1.216     www      12228:         }
1.213     www      12229: 	untie(%bighash);
                   12230:     }
                   12231:     return $okay;
1.31      www      12232: }
                   12233: 
1.210     www      12234: # --------------------------------------------------------------- Clean-up symb
                   12235: 
                   12236: sub symbclean {
                   12237:     my $symb=shift;
1.568     albertel 12238:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12239: # remove version from map
                   12240:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12241: 
1.210     www      12242: # remove version from URL
                   12243:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12244: 
1.507     www      12245: # remove wrapper
                   12246: 
1.510     www      12247:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12248:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12249:     return $symb;
1.409     www      12250: }
                   12251: 
                   12252: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12253: 
                   12254: sub encode_symb {
                   12255:     my ($map,$resid,$url)=@_;
                   12256:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12257: }
1.409     www      12258: 
                   12259: sub decode_symb {
1.568     albertel 12260:     my $symb=shift;
                   12261:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12262:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12263:     return (&fixversion($map),$resid,&fixversion($url));
                   12264: }
                   12265: 
                   12266: sub fixversion {
                   12267:     my $fn=shift;
1.609     banghart 12268:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12269:     my %bighash;
                   12270:     my $uri=&clutter($fn);
1.620     albertel 12271:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12272: # is this cached?
1.599     albertel 12273:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12274:     if (defined($cached)) { return $result; }
                   12275: # unfortunately not cached, or expired
1.620     albertel 12276:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12277: 	    &GDBM_READER(),0640)) {
                   12278:  	if ($bighash{'version_'.$uri}) {
                   12279:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12280:  	    unless (($version eq 'mostrecent') || 
                   12281: 		    ($version==&getversion($uri))) {
1.440     www      12282:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12283:  	    }
                   12284:  	}
                   12285:  	untie %bighash;
1.413     www      12286:     }
1.599     albertel 12287:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12288: }
                   12289: 
                   12290: sub deversion {
                   12291:     my $url=shift;
                   12292:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12293:     return $url;
1.210     www      12294: }
                   12295: 
1.31      www      12296: # ------------------------------------------------------ Return symb list entry
                   12297: 
                   12298: sub symbread {
1.1172.2.66  raeburn  12299:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12300:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12301:     if (defined($env{$cache_str})) {
                   12302:         if ($ignorecachednull) {
                   12303:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12304:         } else {
                   12305:             return $env{$cache_str};
                   12306:         }
                   12307:     }
1.242     www      12308: # no filename provided? try from environment
1.1172.2.54  raeburn  12309:     unless ($thisfn) {
1.620     albertel 12310:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12311:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12312:         }
                   12313:         $thisfn=$env{'request.filename'};
1.44      www      12314:     }
1.569     albertel 12315:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12316: # is that filename actually a symb? Verify, clean, and return
                   12317:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12318: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12319: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12320: 	}
1.242     www      12321:     }
1.44      www      12322:     $thisfn=declutter($thisfn);
1.31      www      12323:     my %hash;
1.37      www      12324:     my %bighash;
                   12325:     my $syval='';
1.620     albertel 12326:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12327:         my $targetfn = $thisfn;
1.609     banghart 12328:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12329:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12330:         }
1.687     albertel 12331: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12332: 	    $targetfn=$1;
                   12333: 	}
1.620     albertel 12334:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12335:                       &GDBM_READER(),0640)) {
1.481     raeburn  12336: 	    $syval=$hash{$targetfn};
1.37      www      12337:             untie(%hash);
                   12338:         }
                   12339: # ---------------------------------------------------------- There was an entry
                   12340:         if ($syval) {
1.601     albertel 12341: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12342: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12343: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12344: 		    #return $env{$cache_str}='';
1.601     albertel 12345: 		#}    
                   12346: 		#$syval.=$1;
                   12347: 	    #}
1.37      www      12348:         } else {
                   12349: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12350:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12351:                             &GDBM_READER(),0640)) {
1.37      www      12352: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12353:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12354:               unless ($ids) { 
                   12355:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12356:               }
                   12357:               unless ($ids) {
                   12358: # alias?
                   12359: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12360:               }
1.37      www      12361:               if ($ids) {
                   12362: # ------------------------------------------------------------------- Has ID(s)
                   12363:                  my @possibilities=split(/\,/,$ids);
1.39      www      12364:                  if ($#possibilities==0) {
                   12365: # ----------------------------------------------- There is only one possibility
1.37      www      12366: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12367: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12368: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12369:                      if (ref($possibles) eq 'HASH') {
                   12370:                          $possibles->{$syval} = 1;
                   12371:                      }
                   12372:                      if ($checkforblock) {
                   12373:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12374:                          if (@blockers) {
                   12375:                              $syval = '';
                   12376:                              return;
                   12377:                          }
                   12378:                      }
                   12379:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12380: # ------------------------------------------ There is more than one possibility
                   12381:                      my $realpossible=0;
1.800     albertel 12382:                      foreach my $id (@possibilities) {
                   12383: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12384:                          my $canaccess;
                   12385:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12386:                              $canaccess = 1;
                   12387:                          } else {
                   12388:                              $canaccess = &allowed('bre',$file);
                   12389:                          }
                   12390:                          if ($canaccess) {
                   12391:          		     my ($mapid,$resid)=split(/\./,$id);
                   12392:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12393:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12394:                                                              $resid,$thisfn);
                   12395:                                  if (ref($possibles) eq 'HASH') {
                   12396:                                      $possibles->{$syval} = 1;
                   12397:                                  }
                   12398:                                  if ($checkforblock) {
                   12399:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12400:                                      unless (@blockers > 0) {
                   12401:                                          $syval = $poss_syval;
                   12402:                                          $realpossible++;
                   12403:                                      }
                   12404:                                  } else {
                   12405:                                      $syval = $poss_syval;
                   12406:                                      $realpossible++;
                   12407:                                  }
                   12408:                              }
1.39      www      12409: 			 }
1.191     harris41 12410:                      }
1.39      www      12411: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12412:                  } else {
                   12413:                      $syval='';
1.37      www      12414:                  }
                   12415: 	      }
1.1172.2.66  raeburn  12416:               untie(%bighash);
1.481     raeburn  12417:            }
1.31      www      12418:         }
1.62      www      12419:         if ($syval) {
1.620     albertel 12420: 	    return $env{$cache_str}=$syval;
1.62      www      12421:         }
1.31      www      12422:     }
1.949     raeburn  12423:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12424:     return $env{$cache_str}='';
1.31      www      12425: }
                   12426: 
                   12427: # ---------------------------------------------------------- Return random seed
                   12428: 
1.32      www      12429: sub numval {
                   12430:     my $txt=shift;
                   12431:     $txt=~tr/A-J/0-9/;
                   12432:     $txt=~tr/a-j/0-9/;
                   12433:     $txt=~tr/K-T/0-9/;
                   12434:     $txt=~tr/k-t/0-9/;
                   12435:     $txt=~tr/U-Z/0-5/;
                   12436:     $txt=~tr/u-z/0-5/;
                   12437:     $txt=~s/\D//g;
1.564     albertel 12438:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12439:     return int($txt);
1.368     albertel 12440: }
                   12441: 
1.484     albertel 12442: sub numval2 {
                   12443:     my $txt=shift;
                   12444:     $txt=~tr/A-J/0-9/;
                   12445:     $txt=~tr/a-j/0-9/;
                   12446:     $txt=~tr/K-T/0-9/;
                   12447:     $txt=~tr/k-t/0-9/;
                   12448:     $txt=~tr/U-Z/0-5/;
                   12449:     $txt=~tr/u-z/0-5/;
                   12450:     $txt=~s/\D//g;
                   12451:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12452:     my $total;
                   12453:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12454:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12455:     return int($total);
                   12456: }
                   12457: 
1.575     albertel 12458: sub numval3 {
                   12459:     use integer;
                   12460:     my $txt=shift;
                   12461:     $txt=~tr/A-J/0-9/;
                   12462:     $txt=~tr/a-j/0-9/;
                   12463:     $txt=~tr/K-T/0-9/;
                   12464:     $txt=~tr/k-t/0-9/;
                   12465:     $txt=~tr/U-Z/0-5/;
                   12466:     $txt=~tr/u-z/0-5/;
                   12467:     $txt=~s/\D//g;
                   12468:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12469:     my $total;
                   12470:     foreach my $val (@txts) { $total+=$val; }
                   12471:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12472:     return $total;
                   12473: }
                   12474: 
1.675     albertel 12475: sub digest {
                   12476:     my ($data)=@_;
                   12477:     my $digest=&Digest::MD5::md5($data);
                   12478:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12479:     my ($e,$f);
                   12480:     {
                   12481:         use integer;
                   12482:         $e=($a+$b);
                   12483:         $f=($c+$d);
                   12484:         if ($_64bit) {
                   12485:             $e=(($e<<32)>>32);
                   12486:             $f=(($f<<32)>>32);
                   12487:         }
                   12488:     }
                   12489:     if (wantarray) {
                   12490: 	return ($e,$f);
                   12491:     } else {
                   12492: 	my $g;
                   12493: 	{
                   12494: 	    use integer;
                   12495: 	    $g=($e+$f);
                   12496: 	    if ($_64bit) {
                   12497: 		$g=(($g<<32)>>32);
                   12498: 	    }
                   12499: 	}
                   12500: 	return $g;
                   12501:     }
                   12502: }
                   12503: 
1.368     albertel 12504: sub latest_rnd_algorithm_id {
1.675     albertel 12505:     return '64bit5';
1.366     albertel 12506: }
1.32      www      12507: 
1.503     albertel 12508: sub get_rand_alg {
                   12509:     my ($courseid)=@_;
1.790     albertel 12510:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12511:     if ($courseid) {
1.620     albertel 12512: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12513:     }
                   12514:     return &latest_rnd_algorithm_id();
                   12515: }
                   12516: 
1.562     albertel 12517: sub validCODE {
                   12518:     my ($CODE)=@_;
                   12519:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12520:     return 0;
                   12521: }
                   12522: 
1.491     albertel 12523: sub getCODE {
1.620     albertel 12524:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12525:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12526: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12527: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12528: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12529:     }
                   12530:     return undef;
                   12531: }
1.1133    foxr     12532: #
                   12533: #  Determines the random seed for a specific context:
                   12534: #
                   12535: # parameters:
                   12536: #   symb      - in course context the symb for the seed.
                   12537: #   course_id - The course id of the form domain_coursenum.
                   12538: #   domain    - Domain for the user.
                   12539: #   course    - Course for the user.
                   12540: #   cenv      - environment of the course.
                   12541: #
                   12542: # NOTE:
                   12543: #   All parameters are picked out of the environment if missing
                   12544: #   or not defined.
                   12545: #   If a symb cannot be determined the current time is used instead.
                   12546: #
                   12547: #  For a given well defined symb, courside, domain, username,
                   12548: #  and course environment, the seed is reproducible.
                   12549: #
1.31      www      12550: sub rndseed {
1.1133    foxr     12551:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12552:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12553:     if (!defined($symb)) {
1.366     albertel 12554: 	unless ($symb=$wsymb) { return time; }
                   12555:     }
1.1146    foxr     12556:     if (!defined $courseid) { 
                   12557: 	$courseid=$wcourseid; 
                   12558:     }
                   12559:     if (!defined $domain) { $domain=$wdomain; }
                   12560:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12561: 
                   12562:     my $which;
                   12563:     if (defined($cenv->{'rndseed'})) {
                   12564: 	$which = $cenv->{'rndseed'};
                   12565:     } else {
                   12566: 	$which =&get_rand_alg($courseid);
                   12567:     }
1.491     albertel 12568:     if (defined(&getCODE())) {
1.675     albertel 12569: 	if ($which eq '64bit5') {
                   12570: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12571: 	} elsif ($which eq '64bit4') {
1.575     albertel 12572: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12573: 	} else {
                   12574: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12575: 	}
1.675     albertel 12576:     } elsif ($which eq '64bit5') {
                   12577: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12578:     } elsif ($which eq '64bit4') {
                   12579: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12580:     } elsif ($which eq '64bit3') {
                   12581: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12582:     } elsif ($which eq '64bit2') {
                   12583: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12584:     } elsif ($which eq '64bit') {
                   12585: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12586:     }
                   12587:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12588: }
                   12589: 
                   12590: sub rndseed_32bit {
                   12591:     my ($symb,$courseid,$domain,$username)=@_;
                   12592:     {
                   12593: 	use integer;
                   12594: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12595: 	my $symbseed=numval($symb) << 22;
                   12596: 	my $namechck=unpack("%32C*",$username) << 17;
                   12597: 	my $nameseed=numval($username) << 12;
                   12598: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12599: 	my $courseseed=unpack("%32C*",$courseid);
                   12600: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12601: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12602: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12603: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12604: 	return $num;
                   12605:     }
                   12606: }
                   12607: 
                   12608: sub rndseed_64bit {
                   12609:     my ($symb,$courseid,$domain,$username)=@_;
                   12610:     {
                   12611: 	use integer;
                   12612: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12613: 	my $symbseed=numval($symb) << 10;
                   12614: 	my $namechck=unpack("%32S*",$username);
                   12615: 	
                   12616: 	my $nameseed=numval($username) << 21;
                   12617: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12618: 	my $courseseed=unpack("%32S*",$courseid);
                   12619: 	
                   12620: 	my $num1=$symbchck+$symbseed+$namechck;
                   12621: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12622: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12623: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12624: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12625: 	return "$num1,$num2";
1.155     albertel 12626:     }
1.366     albertel 12627: }
                   12628: 
1.443     albertel 12629: sub rndseed_64bit2 {
                   12630:     my ($symb,$courseid,$domain,$username)=@_;
                   12631:     {
                   12632: 	use integer;
                   12633: 	# strings need to be an even # of cahracters long, it it is odd the
                   12634:         # last characters gets thrown away
                   12635: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12636: 	my $symbseed=numval($symb) << 10;
                   12637: 	my $namechck=unpack("%32S*",$username.' ');
                   12638: 	
                   12639: 	my $nameseed=numval($username) << 21;
1.501     albertel 12640: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12641: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12642: 	
                   12643: 	my $num1=$symbchck+$symbseed+$namechck;
                   12644: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12645: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12646: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12647: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12648: 	return "$num1,$num2";
                   12649:     }
                   12650: }
                   12651: 
                   12652: sub rndseed_64bit3 {
                   12653:     my ($symb,$courseid,$domain,$username)=@_;
                   12654:     {
                   12655: 	use integer;
                   12656: 	# strings need to be an even # of cahracters long, it it is odd the
                   12657:         # last characters gets thrown away
                   12658: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12659: 	my $symbseed=numval2($symb) << 10;
                   12660: 	my $namechck=unpack("%32S*",$username.' ');
                   12661: 	
                   12662: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12663: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12664: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12665: 	
                   12666: 	my $num1=$symbchck+$symbseed+$namechck;
                   12667: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12668: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12669: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12670: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12671: 	
1.503     albertel 12672: 	return "$num1:$num2";
1.443     albertel 12673:     }
                   12674: }
                   12675: 
1.575     albertel 12676: sub rndseed_64bit4 {
                   12677:     my ($symb,$courseid,$domain,$username)=@_;
                   12678:     {
                   12679: 	use integer;
                   12680: 	# strings need to be an even # of cahracters long, it it is odd the
                   12681:         # last characters gets thrown away
                   12682: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12683: 	my $symbseed=numval3($symb) << 10;
                   12684: 	my $namechck=unpack("%32S*",$username.' ');
                   12685: 	
                   12686: 	my $nameseed=numval3($username) << 21;
                   12687: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12688: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12689: 	
                   12690: 	my $num1=$symbchck+$symbseed+$namechck;
                   12691: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12692: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12693: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12694: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12695: 	
1.575     albertel 12696: 	return "$num1:$num2";
                   12697:     }
                   12698: }
                   12699: 
1.675     albertel 12700: sub rndseed_64bit5 {
                   12701:     my ($symb,$courseid,$domain,$username)=@_;
                   12702:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12703:     return "$num1:$num2";
                   12704: }
                   12705: 
1.366     albertel 12706: sub rndseed_CODE_64bit {
                   12707:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12708:     {
1.366     albertel 12709: 	use integer;
1.443     albertel 12710: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12711: 	my $symbseed=numval2($symb);
1.491     albertel 12712: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12713: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12714: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12715: 	my $num1=$symbseed+$CODEchck;
                   12716: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12717: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12718: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12719: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12720: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12721: 	return "$num1:$num2";
1.366     albertel 12722:     }
                   12723: }
                   12724: 
1.575     albertel 12725: sub rndseed_CODE_64bit4 {
                   12726:     my ($symb,$courseid,$domain,$username)=@_;
                   12727:     {
                   12728: 	use integer;
                   12729: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12730: 	my $symbseed=numval3($symb);
                   12731: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12732: 	my $CODEseed=numval3(&getCODE());
                   12733: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12734: 	my $num1=$symbseed+$CODEchck;
                   12735: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12736: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12737: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12738: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12739: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12740: 	return "$num1:$num2";
                   12741:     }
                   12742: }
                   12743: 
1.675     albertel 12744: sub rndseed_CODE_64bit5 {
                   12745:     my ($symb,$courseid,$domain,$username)=@_;
                   12746:     my $code = &getCODE();
                   12747:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12748:     return "$num1:$num2";
                   12749: }
                   12750: 
1.366     albertel 12751: sub setup_random_from_rndseed {
                   12752:     my ($rndseed)=@_;
1.503     albertel 12753:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12754: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12755:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12756:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12757:         } else {
                   12758:             &Math::Random::random_set_seed($num1,$num2);
                   12759:         }
1.366     albertel 12760:     } else {
                   12761: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12762:     }
1.36      albertel 12763: }
                   12764: 
1.474     albertel 12765: sub latest_receipt_algorithm_id {
1.835     albertel 12766:     return 'receipt3';
1.474     albertel 12767: }
                   12768: 
1.480     www      12769: sub recunique {
                   12770:     my $fucourseid=shift;
                   12771:     my $unique;
1.835     albertel 12772:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12773: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12774: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12775:     } else {
                   12776: 	$unique=$perlvar{'lonReceipt'};
                   12777:     }
                   12778:     return unpack("%32C*",$unique);
                   12779: }
                   12780: 
                   12781: sub recprefix {
                   12782:     my $fucourseid=shift;
                   12783:     my $prefix;
1.835     albertel 12784:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12785: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12786: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12787:     } else {
                   12788: 	$prefix=$perlvar{'lonHostID'};
                   12789:     }
                   12790:     return unpack("%32C*",$prefix);
                   12791: }
                   12792: 
1.76      www      12793: sub ireceipt {
1.474     albertel 12794:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12795: 
                   12796:     my $return =&recprefix($fucourseid).'-';
                   12797: 
                   12798:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12799: 	$env{'request.state'} eq 'construct') {
                   12800: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12801: 	return $return;
                   12802:     }
                   12803: 
1.76      www      12804:     my $cuname=unpack("%32C*",$funame);
                   12805:     my $cudom=unpack("%32C*",$fudom);
                   12806:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12807:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12808:     my $cunique=&recunique($fucourseid);
1.474     albertel 12809:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12810:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12811: 
1.790     albertel 12812: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12813: 			       
                   12814: 	$return.= ($cunique%$cuname+
                   12815: 		   $cunique%$cudom+
                   12816: 		   $cusymb%$cuname+
                   12817: 		   $cusymb%$cudom+
                   12818: 		   $cucourseid%$cuname+
                   12819: 		   $cucourseid%$cudom+
                   12820: 		   $cpart%$cuname+
                   12821: 		   $cpart%$cudom);
                   12822:     } else {
                   12823: 	$return.= ($cunique%$cuname+
                   12824: 		   $cunique%$cudom+
                   12825: 		   $cusymb%$cuname+
                   12826: 		   $cusymb%$cudom+
                   12827: 		   $cucourseid%$cuname+
                   12828: 		   $cucourseid%$cudom);
                   12829:     }
                   12830:     return $return;
1.76      www      12831: }
                   12832: 
                   12833: sub receipt {
1.474     albertel 12834:     my ($part)=@_;
1.790     albertel 12835:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12836:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12837: }
1.260     ng       12838: 
1.790     albertel 12839: sub whichuser {
                   12840:     my ($passedsymb)=@_;
                   12841:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12842:     if (defined($env{'form.grade_symb'})) {
                   12843: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12844: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12845: 	if (!$allowed &&
                   12846: 	    exists($env{'request.course.sec'}) &&
                   12847: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12848: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12849: 			      '/'.$env{'request.course.sec'});
                   12850: 	}
                   12851: 	if ($allowed) {
                   12852: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12853: 	    $courseid=$tmp_courseid;
                   12854: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12855: 	    ($name)=&get_env_multiple('form.grade_username');
                   12856: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12857: 	}
                   12858:     }
                   12859:     if (!$passedsymb) {
                   12860: 	$symb=&symbread();
                   12861:     } else {
                   12862: 	$symb=$passedsymb;
                   12863:     }
                   12864:     $courseid=$env{'request.course.id'};
                   12865:     $domain=$env{'user.domain'};
                   12866:     $name=$env{'user.name'};
                   12867:     if ($name eq 'public' && $domain eq 'public') {
                   12868: 	if (!defined($env{'form.username'})) {
                   12869: 	    $env{'form.username'}.=time.rand(10000000);
                   12870: 	}
                   12871: 	$name.=$env{'form.username'};
                   12872:     }
                   12873:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12874: 
                   12875: }
                   12876: 
1.36      albertel 12877: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12878: # returns either the contents of the file or 
                   12879: # -1 if the file doesn't exist
1.481     raeburn  12880: #
                   12881: # if the target is a file that was uploaded via DOCS, 
                   12882: # a check will be made to see if a current copy exists on the local server,
                   12883: # if it does this will be served, otherwise a copy will be retrieved from
                   12884: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12885: # the local server.   
1.472     albertel 12886: 
1.36      albertel 12887: sub getfile {
1.538     albertel 12888:     my ($file) = @_;
1.609     banghart 12889:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12890:     &repcopy($file);
                   12891:     return &readfile($file);
                   12892: }
                   12893: 
                   12894: sub repcopy_userfile {
                   12895:     my ($file)=@_;
1.1142    raeburn  12896:     my $londocroot = $perlvar{'lonDocRoot'};
                   12897:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12898:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12899:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12900: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12901:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12902:     if (-e "$file") {
1.828     www      12903: # we already have a local copy, check it out
1.538     albertel 12904: 	my @fileinfo = stat($file);
1.828     www      12905: 	my $rtncode;
                   12906: 	my $info;
1.538     albertel 12907: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12908: 	if ($lwpresp ne 'ok') {
1.828     www      12909: # there is no such file anymore, even though we had a local copy
1.482     albertel 12910: 	    if ($rtncode eq '404') {
1.538     albertel 12911: 		unlink($file);
1.482     albertel 12912: 	    }
                   12913: 	    return -1;
                   12914: 	}
                   12915: 	if ($info < $fileinfo[9]) {
1.828     www      12916: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12917: 	    return 'ok';
1.828     www      12918: 	} else {
                   12919: # the file is outdated, get rid of it
                   12920: 	    unlink($file);
1.482     albertel 12921: 	}
1.828     www      12922:     }
                   12923: # one way or the other, at this point, we don't have the file
                   12924: # construct the correct path for the file
                   12925:     my @parts = ($cdom,$cnum); 
                   12926:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12927: 	push @parts, split(/\//,$1);
                   12928:     }
                   12929:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12930:     foreach my $part (@parts) {
                   12931: 	$path .= '/'.$part;
                   12932: 	if (!-e $path) {
                   12933: 	    mkdir($path,0770);
1.482     albertel 12934: 	}
                   12935:     }
1.828     www      12936: # now the path exists for sure
                   12937: # get a user agent
                   12938:     my $ua=new LWP::UserAgent;
                   12939:     my $transferfile=$file.'.in.transfer';
                   12940: # FIXME: this should flock
                   12941:     if (-e $transferfile) { return 'ok'; }
                   12942:     my $request;
                   12943:     $uri=~s/^\///;
1.980     raeburn  12944:     my $homeserver = &homeserver($cnum,$cdom);
                   12945:     my $protocol = $protocol{$homeserver};
                   12946:     $protocol = 'http' if ($protocol ne 'https');
                   12947:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12948:     my $response=$ua->request($request,$transferfile);
                   12949: # did it work?
                   12950:     if ($response->is_error()) {
                   12951: 	unlink($transferfile);
                   12952: 	&logthis("Userfile repcopy failed for $uri");
                   12953: 	return -1;
                   12954:     }
                   12955: # worked, rename the transfer file
                   12956:     rename($transferfile,$file);
1.607     raeburn  12957:     return 'ok';
1.481     raeburn  12958: }
                   12959: 
1.517     albertel 12960: sub tokenwrapper {
                   12961:     my $uri=shift;
1.980     raeburn  12962:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12963:     $uri=~s|^/||;
1.620     albertel 12964:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12965:     my $token=$1;
1.552     albertel 12966:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12967:     if ($udom && $uname && $file) {
                   12968: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12969:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12970:         my $homeserver = &homeserver($uname,$udom);
                   12971:         my $protocol = $protocol{$homeserver};
                   12972:         $protocol = 'http' if ($protocol ne 'https');
                   12973:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12974:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12975:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12976:     } else {
                   12977:         return '/adm/notfound.html';
                   12978:     }
                   12979: }
                   12980: 
1.828     www      12981: # call with reqtype HEAD: get last modification time
                   12982: # call with reqtype GET: get the file contents
                   12983: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12984: #
1.481     raeburn  12985: sub getuploaded {
                   12986:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12987:     $uri=~s/^\///;
1.980     raeburn  12988:     my $homeserver = &homeserver($cnum,$cdom);
                   12989:     my $protocol = $protocol{$homeserver};
                   12990:     $protocol = 'http' if ($protocol ne 'https');
                   12991:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12992:     my $ua=new LWP::UserAgent;
                   12993:     my $request=new HTTP::Request($reqtype,$uri);
                   12994:     my $response=$ua->request($request);
                   12995:     $$rtncode = $response->code;
1.482     albertel 12996:     if (! $response->is_success()) {
                   12997: 	return 'failed';
                   12998:     }      
                   12999:     if ($reqtype eq 'HEAD') {
1.486     www      13000: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13001:     } elsif ($reqtype eq 'GET') {
                   13002: 	$$info = $response->content;
1.472     albertel 13003:     }
1.482     albertel 13004:     return 'ok';
1.36      albertel 13005: }
                   13006: 
1.481     raeburn  13007: sub readfile {
                   13008:     my $file = shift;
                   13009:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13010:     my $fh;
1.1172.2.96  raeburn  13011:     open($fh,"<",$file);
1.481     raeburn  13012:     my $a='';
1.800     albertel 13013:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13014:     return $a;
                   13015: }
                   13016: 
1.36      albertel 13017: sub filelocation {
1.590     banghart 13018:     my ($dir,$file) = @_;
                   13019:     my $location;
                   13020:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13021: 
                   13022:     if ($file =~ m-^/adm/-) {
                   13023: 	$file=~s-^/adm/wrapper/-/-;
                   13024: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13025:     }
1.882     albertel 13026: 
1.1139    www      13027:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13028:         $location = $file;
1.609     banghart 13029:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13030:         my ($udom,$uname,$filename)=
1.811     albertel 13031:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13032:         my $home=&homeserver($uname,$udom);
                   13033:         my $is_me=0;
                   13034:         my @ids=&current_machine_ids();
                   13035:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13036:         if ($is_me) {
1.1117    foxr     13037:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13038:         } else {
                   13039:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13040:   	      $udom.'/'.$uname.'/'.$filename;
                   13041:         }
1.882     albertel 13042:     } elsif ($file =~ m-^/adm/-) {
                   13043: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13044:     } else {
                   13045:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13046:         $file=~s:^/(res|priv)/:/:;
                   13047:         my $space=$1;
1.590     banghart 13048:         if ( !( $file =~ m:^/:) ) {
                   13049:             $location = $dir. '/'.$file;
                   13050:         } else {
1.1142    raeburn  13051:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13052:         }
1.59      albertel 13053:     }
1.590     banghart 13054:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13055:     while ($location=~m{/\.\./}) {
                   13056: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13057: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13058: 	} else {
                   13059: 	    $location=~ s{/\.\./}{/}g;
                   13060: 	}
                   13061:     } #remove dir/..
1.590     banghart 13062:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13063:     return $location;
1.46      www      13064: }
1.36      albertel 13065: 
1.46      www      13066: sub hreflocation {
                   13067:     my ($dir,$file)=@_;
1.980     raeburn  13068:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13069: 	$file=filelocation($dir,$file);
1.700     albertel 13070:     } elsif ($file=~m-^/adm/-) {
                   13071: 	$file=~s-^/adm/wrapper/-/-;
                   13072: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13073:     }
                   13074:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13075: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13076:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13077: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13078: 	        {/uploaded/$1/$2/}x;
1.46      www      13079:     }
1.913     albertel 13080:     if ($file=~ m{^/userfiles/}) {
                   13081: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13082:     }
1.462     albertel 13083:     return $file;
1.465     albertel 13084: }
                   13085: 
1.1139    www      13086: 
                   13087: 
                   13088: 
                   13089: 
1.465     albertel 13090: sub current_machine_domains {
1.853     albertel 13091:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13092: }
                   13093: 
                   13094: sub machine_domains {
                   13095:     my ($hostname) = @_;
1.465     albertel 13096:     my @domains;
1.838     albertel 13097:     my %hostname = &all_hostnames();
1.465     albertel 13098:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13099: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13100: 	if ($hostname eq $name) {
1.844     albertel 13101: 	    push(@domains,&host_domain($id));
1.465     albertel 13102: 	}
                   13103:     }
                   13104:     return @domains;
                   13105: }
                   13106: 
                   13107: sub current_machine_ids {
1.853     albertel 13108:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13109: }
                   13110: 
                   13111: sub machine_ids {
                   13112:     my ($hostname) = @_;
                   13113:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13114:     my @ids;
1.888     albertel 13115:     my %name_to_host = &all_names();
1.889     albertel 13116:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13117: 	return @{ $name_to_host{$hostname} };
                   13118:     }
                   13119:     return;
1.31      www      13120: }
                   13121: 
1.824     raeburn  13122: sub additional_machine_domains {
                   13123:     my @domains;
1.1172.2.96  raeburn  13124:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13125:     while( my $line = <$fh>) {
                   13126:         $line =~ s/\s//g;
                   13127:         push(@domains,$line);
                   13128:     }
                   13129:     return @domains;
                   13130: }
                   13131: 
                   13132: sub default_login_domain {
                   13133:     my $domain = $perlvar{'lonDefDomain'};
                   13134:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13135:     foreach my $posdom (&current_machine_domains(),
                   13136:                         &additional_machine_domains()) {
                   13137:         if (lc($posdom) eq lc($testdomain)) {
                   13138:             $domain=$posdom;
                   13139:             last;
                   13140:         }
                   13141:     }
                   13142:     return $domain;
                   13143: }
                   13144: 
1.1172.2.106  raeburn  13145: sub shared_institution {
                   13146:     my ($dom) = @_;
                   13147:     my $same_intdom;
                   13148:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13149:     if ($hostintdom ne '') {
                   13150:         my %iphost = &get_iphost();
                   13151:         my $primary_id = &domain($dom,'primary');
                   13152:         my $primary_ip = &get_host_ip($primary_id);
                   13153:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13154:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13155:                 my $intdom = &internet_dom($id);
                   13156:                 if ($intdom eq $hostintdom) {
                   13157:                     $same_intdom = 1;
                   13158:                     last;
                   13159:                 }
                   13160:             }
                   13161:         }
                   13162:     }
                   13163:     return $same_intdom;
                   13164: }
                   13165: 
1.31      www      13166: # ------------------------------------------------------------- Declutters URLs
                   13167: 
                   13168: sub declutter {
                   13169:     my $thisfn=shift;
1.569     albertel 13170:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13171:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13172:         $thisfn=~s{^/home/httpd/html}{};
                   13173:     }
1.31      www      13174:     $thisfn=~s/^\///;
1.697     albertel 13175:     $thisfn=~s|^adm/wrapper/||;
                   13176:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13177:     $thisfn=~s/^res\///;
1.1172    bisitz   13178:     $thisfn=~s/^priv\///;
1.1032    raeburn  13179:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13180:         $thisfn=~s/\?.+$//;
                   13181:     }
1.268     www      13182:     return $thisfn;
                   13183: }
                   13184: 
                   13185: # ------------------------------------------------------------- Clutter up URLs
                   13186: 
                   13187: sub clutter {
                   13188:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13189:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13190: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13191:        $thisfn='/res'.$thisfn; 
                   13192:     }
1.1031    raeburn  13193:     if ($thisfn !~m|^/adm|) {
                   13194: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13195: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13196: 	} else {
                   13197: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13198: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13199: 	    if ($embstyle eq 'ssi'
                   13200: 		|| ($embstyle eq 'hdn')
                   13201: 		|| ($embstyle eq 'rat')
                   13202: 		|| ($embstyle eq 'prv')
                   13203: 		|| ($embstyle eq 'ign')) {
                   13204: 		#do nothing with these
                   13205: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13206: 		|| ($embstyle eq 'emb')
                   13207: 		|| ($embstyle eq 'wrp')) {
                   13208: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13209: 	    } elsif ($embstyle eq 'unk'
                   13210: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13211: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13212: 	    } else {
1.718     www      13213: #		&logthis("Got a blank emb style");
1.695     albertel 13214: 	    }
1.694     albertel 13215: 	}
                   13216:     }
1.31      www      13217:     return $thisfn;
1.12      www      13218: }
                   13219: 
1.787     albertel 13220: sub clutter_with_no_wrapper {
                   13221:     my $uri = &clutter(shift);
                   13222:     if ($uri =~ m-^/adm/-) {
                   13223: 	$uri =~ s-^/adm/wrapper/-/-;
                   13224: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13225:     }
                   13226:     return $uri;
                   13227: }
                   13228: 
1.557     albertel 13229: sub freeze_escape {
                   13230:     my ($value)=@_;
                   13231:     if (ref($value)) {
                   13232: 	$value=&nfreeze($value);
                   13233: 	return '__FROZEN__'.&escape($value);
                   13234:     }
                   13235:     return &escape($value);
                   13236: }
                   13237: 
1.11      www      13238: 
1.557     albertel 13239: sub thaw_unescape {
                   13240:     my ($value)=@_;
                   13241:     if ($value =~ /^__FROZEN__/) {
                   13242: 	substr($value,0,10,undef);
                   13243: 	$value=&unescape($value);
                   13244: 	return &thaw($value);
                   13245:     }
                   13246:     return &unescape($value);
                   13247: }
                   13248: 
1.436     albertel 13249: sub correct_line_ends {
                   13250:     my ($result)=@_;
                   13251:     $$result =~s/\r\n/\n/mg;
                   13252:     $$result =~s/\r/\n/mg;
1.415     albertel 13253: }
1.1       albertel 13254: # ================================================================ Main Program
                   13255: 
1.184     www      13256: sub goodbye {
1.204     albertel 13257:    &logthis("Starting Shut down");
1.443     albertel 13258: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13259:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13260: #converted
1.599     albertel 13261: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13262:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13263: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13264: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13265: #1.1 only
1.870     albertel 13266: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13267: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13268: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13269: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13270:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13271:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13272:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13273:    &flushcourselogs();
                   13274:    &logthis("Shutting down");
                   13275: }
                   13276: 
1.852     albertel 13277: sub get_dns {
1.1172.2.17  raeburn  13278:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13279:     if (!$ignore_cache) {
                   13280: 	my ($content,$cached)=
                   13281: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13282: 	if ($cached) {
1.1172.2.17  raeburn  13283: 	    &$func($content,$hashref);
1.869     albertel 13284: 	    return;
                   13285: 	}
                   13286:     }
                   13287: 
                   13288:     my %alldns;
1.1172.2.96  raeburn  13289:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13290:         foreach my $dns (<$config>) {
                   13291: 	    next if ($dns !~ /^\^(\S*)/x);
                   13292:             my $line = $1;
                   13293:             my ($host,$protocol) = split(/:/,$line);
                   13294:             if ($protocol ne 'https') {
                   13295:                 $protocol = 'http';
                   13296:             }
                   13297: 	    $alldns{$host} = $protocol;
1.979     raeburn  13298:         }
1.1172.2.96  raeburn  13299:         close($config);
1.869     albertel 13300:     }
                   13301:     while (%alldns) {
1.1172.2.52  raeburn  13302: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13303: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13304:         $ua->timeout(30);
1.979     raeburn  13305: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13306: 	my $response=$ua->request($request);
1.979     raeburn  13307:         delete($alldns{$dns});
1.852     albertel 13308: 	next if ($response->is_error());
                   13309: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13310:         unless ($nocache) {
1.1172.2.23  raeburn  13311: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13312:         }
                   13313: 	&$func(\@content,$hashref);
1.869     albertel 13314: 	return;
1.852     albertel 13315:     }
1.871     albertel 13316:     my $which = (split('/',$url))[3];
                   13317:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13318:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13319:         my @content = <$config>;
                   13320:         &$func(\@content,$hashref);
                   13321:     }
1.1172.2.17  raeburn  13322:     return;
                   13323: }
                   13324: 
                   13325: # ------------------------------------------------------Get DNS checksums file
                   13326: sub parse_dns_checksums_tab {
                   13327:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13328:     my $lonhost = $perlvar{'lonHostID'};
                   13329:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13330:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13331:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13332:     my $webconfdir = '/etc/httpd/conf';
                   13333:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13334:         $webconfdir = '/etc/apache2';
                   13335:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13336:         if ($1 >= 10) {
                   13337:             $webconfdir = '/etc/apache2';
                   13338:         }
                   13339:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13340:         if ($1 >= 10.0) {
                   13341:             $webconfdir = '/etc/apache2';
                   13342:         }
                   13343:     }
1.1172.2.17  raeburn  13344:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13345:     my (%chksum,%revnum);
                   13346:     if (ref($lines) eq 'ARRAY') {
                   13347:         chomp(@{$lines});
1.1172.2.34  raeburn  13348:         my $version = shift(@{$lines});
                   13349:         if ($version eq $release) {
1.1172.2.17  raeburn  13350:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13351:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13352:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13353:                     if ($webconfdir eq '/etc/apache2') {
                   13354:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13355:                     }
                   13356:                 }
1.1172.2.34  raeburn  13357:                 $chksum{$file} = $shasum;
                   13358:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13359:             }
                   13360:             if (ref($hashref) eq 'HASH') {
                   13361:                 %{$hashref} = (
                   13362:                                 sums     => \%chksum,
                   13363:                                 versions => \%revnum,
                   13364:                               );
                   13365:             }
                   13366:         }
                   13367:     }
1.869     albertel 13368:     return;
1.852     albertel 13369: }
1.1172.2.17  raeburn  13370: 
                   13371: sub fetch_dns_checksums {
                   13372:     my %checksums;
1.1172.2.34  raeburn  13373:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13374:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13375:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13376:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13377:              \%checksums);
                   13378:     return \%checksums;
                   13379: }
                   13380: 
1.327     albertel 13381: # ------------------------------------------------------------ Read domain file
                   13382: {
1.852     albertel 13383:     my $loaded;
1.846     albertel 13384:     my %domain;
                   13385: 
1.852     albertel 13386:     sub parse_domain_tab {
                   13387: 	my ($lines) = @_;
                   13388: 	foreach my $line (@$lines) {
                   13389: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13390: 
1.846     albertel 13391: 	    chomp($line);
1.852     albertel 13392: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13393: 	    my %this_domain;
                   13394: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13395: 			       'lang_def', 'city', 'longi', 'lati',
                   13396: 			       'primary') {
                   13397: 		$this_domain{$field} = shift(@elements);
                   13398: 	    }
                   13399: 	    $domain{$name} = \%this_domain;
1.852     albertel 13400: 	}
                   13401:     }
1.864     albertel 13402: 
                   13403:     sub reset_domain_info {
                   13404: 	undef($loaded);
                   13405: 	undef(%domain);
                   13406:     }
                   13407: 
1.852     albertel 13408:     sub load_domain_tab {
1.1172.2.70  raeburn  13409: 	my ($ignore_cache,$nocache) = @_;
                   13410: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13411: 	my $fh;
1.1172.2.96  raeburn  13412: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13413: 	    my @lines = <$fh>;
                   13414: 	    &parse_domain_tab(\@lines);
1.448     albertel 13415: 	}
1.852     albertel 13416: 	close($fh);
                   13417: 	$loaded = 1;
1.327     albertel 13418:     }
1.846     albertel 13419: 
                   13420:     sub domain {
1.852     albertel 13421: 	&load_domain_tab() if (!$loaded);
                   13422: 
1.846     albertel 13423: 	my ($name,$what) = @_;
                   13424: 	return if ( !exists($domain{$name}) );
                   13425: 
                   13426: 	if (!$what) {
                   13427: 	    return $domain{$name}{'description'};
                   13428: 	}
                   13429: 	return $domain{$name}{$what};
                   13430:     }
1.974     raeburn  13431: 
                   13432:     sub domain_info {
                   13433:         &load_domain_tab() if (!$loaded);
                   13434:         return %domain;
                   13435:     }
                   13436: 
1.327     albertel 13437: }
                   13438: 
                   13439: 
1.1       albertel 13440: # ------------------------------------------------------------- Read hosts file
                   13441: {
1.838     albertel 13442:     my %hostname;
1.844     albertel 13443:     my %hostdom;
1.845     albertel 13444:     my %libserv;
1.852     albertel 13445:     my $loaded;
1.888     albertel 13446:     my %name_to_host;
1.1074    raeburn  13447:     my %internetdom;
1.1107    raeburn  13448:     my %LC_dns_serv;
1.852     albertel 13449: 
                   13450:     sub parse_hosts_tab {
                   13451: 	my ($file) = @_;
                   13452: 	foreach my $configline (@$file) {
                   13453: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13454:             chomp($configline);
                   13455: 	    if ($configline =~ /^\^/) {
                   13456:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13457:                     $LC_dns_serv{$1} = 1;
                   13458:                 }
                   13459:                 next;
                   13460:             }
1.1074    raeburn  13461: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13462: 	    $name=~s/\s//g;
                   13463: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13464:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13465:                     my $curr = $hostname{$id};
                   13466:                     my $skip;
                   13467:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13468:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13469:                             $skip = 1;
                   13470:                         } else {
                   13471:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13472:                         }
                   13473:                     }
                   13474:                     unless ($skip) {
                   13475:                         push(@{$name_to_host{$name}},$id);
                   13476:                     }
                   13477:                 } else {
                   13478:                     push(@{$name_to_host{$name}},$id);
                   13479:                 }
1.852     albertel 13480: 		$hostname{$id}=$name;
                   13481: 		$hostdom{$id}=$domain;
                   13482: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13483:                 if (defined($protocol)) {
                   13484:                     if ($protocol eq 'https') {
                   13485:                         $protocol{$id} = $protocol;
                   13486:                     } else {
                   13487:                         $protocol{$id} = 'http'; 
                   13488:                     }
1.968     raeburn  13489:                 } else {
1.969     raeburn  13490:                     $protocol{$id} = 'http';
1.968     raeburn  13491:                 }
1.1074    raeburn  13492:                 if (defined($intdom)) {
                   13493:                     $internetdom{$id} = $intdom;
                   13494:                 }
1.852     albertel 13495: 	    }
                   13496: 	}
                   13497:     }
1.864     albertel 13498:     
                   13499:     sub reset_hosts_info {
1.897     albertel 13500: 	&purge_remembered();
1.864     albertel 13501: 	&reset_domain_info();
                   13502: 	&reset_hosts_ip_info();
1.892     albertel 13503: 	undef(%name_to_host);
1.864     albertel 13504: 	undef(%hostname);
                   13505: 	undef(%hostdom);
                   13506: 	undef(%libserv);
                   13507: 	undef($loaded);
                   13508:     }
1.1       albertel 13509: 
1.852     albertel 13510:     sub load_hosts_tab {
1.1172.2.70  raeburn  13511: 	my ($ignore_cache,$nocache) = @_;
                   13512: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13513: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13514: 	my @config = <$config>;
                   13515: 	&parse_hosts_tab(\@config);
                   13516: 	close($config);
                   13517: 	$loaded=1;
1.1       albertel 13518:     }
1.852     albertel 13519: 
1.838     albertel 13520:     sub hostname {
1.852     albertel 13521: 	&load_hosts_tab() if (!$loaded);
                   13522: 
1.838     albertel 13523: 	my ($lonid) = @_;
                   13524: 	return $hostname{$lonid};
                   13525:     }
1.845     albertel 13526: 
1.838     albertel 13527:     sub all_hostnames {
1.852     albertel 13528: 	&load_hosts_tab() if (!$loaded);
                   13529: 
1.838     albertel 13530: 	return %hostname;
                   13531:     }
1.845     albertel 13532: 
1.888     albertel 13533:     sub all_names {
1.1172.2.70  raeburn  13534:         my ($ignore_cache,$nocache) = @_;
                   13535: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13536: 
                   13537: 	return %name_to_host;
                   13538:     }
                   13539: 
1.974     raeburn  13540:     sub all_host_domain {
                   13541:         &load_hosts_tab() if (!$loaded);
                   13542:         return %hostdom;
                   13543:     }
                   13544: 
1.845     albertel 13545:     sub is_library {
1.852     albertel 13546: 	&load_hosts_tab() if (!$loaded);
                   13547: 
1.845     albertel 13548: 	return exists($libserv{$_[0]});
                   13549:     }
                   13550: 
                   13551:     sub all_library {
1.852     albertel 13552: 	&load_hosts_tab() if (!$loaded);
                   13553: 
1.845     albertel 13554: 	return %libserv;
                   13555:     }
                   13556: 
1.1062    droeschl 13557:     sub unique_library {
                   13558: 	#2x reverse removes all hostnames that appear more than once
                   13559:         my %unique = reverse &all_library();
                   13560:         return reverse %unique;
                   13561:     }
                   13562: 
1.841     albertel 13563:     sub get_servers {
1.852     albertel 13564: 	&load_hosts_tab() if (!$loaded);
                   13565: 
1.841     albertel 13566: 	my ($domain,$type) = @_;
                   13567: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13568: 	                                          : %hostname;
                   13569: 	my %result;
1.842     albertel 13570: 	if (ref($domain) eq 'ARRAY') {
                   13571: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13572: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13573: 		    $result{$host} = $hostname;
                   13574: 		}
                   13575: 	    }
                   13576: 	} else {
                   13577: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13578: 		if ($hostdom{$host} eq $domain) {
                   13579: 		    $result{$host} = $hostname;
                   13580: 		}
1.841     albertel 13581: 	    }
                   13582: 	}
                   13583: 	return %result;
                   13584:     }
1.845     albertel 13585: 
1.1062    droeschl 13586:     sub get_unique_servers {
                   13587:         my %unique = reverse &get_servers(@_);
                   13588: 	return reverse %unique;
                   13589:     }
                   13590: 
1.844     albertel 13591:     sub host_domain {
1.852     albertel 13592: 	&load_hosts_tab() if (!$loaded);
                   13593: 
1.844     albertel 13594: 	my ($lonid) = @_;
                   13595: 	return $hostdom{$lonid};
                   13596:     }
                   13597: 
1.841     albertel 13598:     sub all_domains {
1.852     albertel 13599: 	&load_hosts_tab() if (!$loaded);
                   13600: 
1.841     albertel 13601: 	my %seen;
                   13602: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13603: 	return @uniq;
                   13604:     }
1.1074    raeburn  13605: 
                   13606:     sub internet_dom {
                   13607:         &load_hosts_tab() if (!$loaded);
                   13608: 
                   13609:         my ($lonid) = @_;
                   13610:         return $internetdom{$lonid};
                   13611:     }
1.1107    raeburn  13612: 
                   13613:     sub is_LC_dns {
                   13614:         &load_hosts_tab() if (!$loaded);
                   13615: 
                   13616:         my ($hostname) = @_;
                   13617:         return exists($LC_dns_serv{$hostname});
                   13618:     }
                   13619: 
1.1       albertel 13620: }
                   13621: 
1.847     albertel 13622: { 
                   13623:     my %iphost;
1.856     albertel 13624:     my %name_to_ip;
                   13625:     my %lonid_to_ip;
1.869     albertel 13626: 
1.847     albertel 13627:     sub get_hosts_from_ip {
                   13628: 	my ($ip) = @_;
                   13629: 	my %iphosts = &get_iphost();
                   13630: 	if (ref($iphosts{$ip})) {
                   13631: 	    return @{$iphosts{$ip}};
                   13632: 	}
                   13633: 	return;
1.839     albertel 13634:     }
1.864     albertel 13635:     
                   13636:     sub reset_hosts_ip_info {
                   13637: 	undef(%iphost);
                   13638: 	undef(%name_to_ip);
                   13639: 	undef(%lonid_to_ip);
                   13640:     }
1.856     albertel 13641: 
                   13642:     sub get_host_ip {
                   13643: 	my ($lonid) = @_;
                   13644: 	if (exists($lonid_to_ip{$lonid})) {
                   13645: 	    return $lonid_to_ip{$lonid};
                   13646: 	}
                   13647: 	my $name=&hostname($lonid);
                   13648:    	my $ip = gethostbyname($name);
                   13649: 	return if (!$ip || length($ip) ne 4);
                   13650: 	$ip=inet_ntoa($ip);
                   13651: 	$name_to_ip{$name}   = $ip;
                   13652: 	$lonid_to_ip{$lonid} = $ip;
                   13653: 	return $ip;
                   13654:     }
1.847     albertel 13655:     
                   13656:     sub get_iphost {
1.1172.2.70  raeburn  13657: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13658: 
1.869     albertel 13659: 	if (!$ignore_cache) {
                   13660: 	    if (%iphost) {
                   13661: 		return %iphost;
                   13662: 	    }
                   13663: 	    my ($ip_info,$cached)=
                   13664: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13665: 	    if ($cached) {
                   13666: 		%iphost      = %{$ip_info->[0]};
                   13667: 		%name_to_ip  = %{$ip_info->[1]};
                   13668: 		%lonid_to_ip = %{$ip_info->[2]};
                   13669: 		return %iphost;
                   13670: 	    }
                   13671: 	}
1.894     albertel 13672: 
                   13673: 	# get yesterday's info for fallback
                   13674: 	my %old_name_to_ip;
                   13675: 	my ($ip_info,$cached)=
                   13676: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13677: 	if ($cached) {
                   13678: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13679: 	}
                   13680: 
1.1172.2.70  raeburn  13681: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13682: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13683: 	    my $ip;
                   13684: 	    if (!exists($name_to_ip{$name})) {
                   13685: 		$ip = gethostbyname($name);
                   13686: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13687: 		    if (defined($old_name_to_ip{$name})) {
                   13688: 			$ip = $old_name_to_ip{$name};
                   13689: 			&logthis("Can't find $name defaulting to old $ip");
                   13690: 		    } else {
                   13691: 			&logthis("Name $name no IP found");
                   13692: 			next;
                   13693: 		    }
                   13694: 		} else {
                   13695: 		    $ip=inet_ntoa($ip);
1.847     albertel 13696: 		}
                   13697: 		$name_to_ip{$name} = $ip;
                   13698: 	    } else {
                   13699: 		$ip = $name_to_ip{$name};
1.653     albertel 13700: 	    }
1.888     albertel 13701: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13702: 		$lonid_to_ip{$id} = $ip;
                   13703: 	    }
                   13704: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13705: 	}
1.1172.2.70  raeburn  13706:         unless ($nocache) {
                   13707: 	    &do_cache_new('iphost','iphost',
                   13708: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13709: 		          48*60*60);
                   13710:         }
1.869     albertel 13711: 
1.847     albertel 13712: 	return %iphost;
1.598     albertel 13713:     }
                   13714: 
1.992     raeburn  13715:     #
                   13716:     #  Given a DNS returns the loncapa host name for that DNS 
                   13717:     # 
                   13718:     sub host_from_dns {
                   13719:         my ($dns) = @_;
                   13720:         my @hosts;
                   13721:         my $ip;
                   13722: 
1.993     raeburn  13723:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13724:             $ip = $name_to_ip{$dns};
                   13725:         }
                   13726:         if (!$ip) {
                   13727:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13728:             if (length($ip) == 4) { 
                   13729: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13730:             }
                   13731:         }
                   13732:         if ($ip) {
                   13733: 	    @hosts = get_hosts_from_ip($ip);
                   13734: 	    return $hosts[0];
                   13735:         }
                   13736:         return undef;
1.986     foxr     13737:     }
1.992     raeburn  13738: 
1.1074    raeburn  13739:     sub get_internet_names {
                   13740:         my ($lonid) = @_;
                   13741:         return if ($lonid eq '');
                   13742:         my ($idnref,$cached)=
                   13743:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13744:         if ($cached) {
                   13745:             return $idnref;
                   13746:         }
                   13747:         my $ip = &get_host_ip($lonid);
                   13748:         my @hosts = &get_hosts_from_ip($ip);
                   13749:         my %iphost = &get_iphost();
                   13750:         my (@idns,%seen);
                   13751:         foreach my $id (@hosts) {
                   13752:             my $dom = &host_domain($id);
                   13753:             my $prim_id = &domain($dom,'primary');
                   13754:             my $prim_ip = &get_host_ip($prim_id);
                   13755:             next if ($seen{$prim_ip});
                   13756:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13757:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13758:                     my $intdom = &internet_dom($id);
                   13759:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13760:                         push(@idns,$intdom);
                   13761:                     }
                   13762:                 }
                   13763:             }
                   13764:             $seen{$prim_ip} = 1;
                   13765:         }
1.1172.2.23  raeburn  13766:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13767:     }
                   13768: 
1.986     foxr     13769: }
                   13770: 
1.1079    raeburn  13771: sub all_loncaparevs {
1.1172.2.39  raeburn  13772:     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  13773: }
                   13774: 
1.1172.2.27  raeburn  13775: # ------------------------------------------------------- Read loncaparev table
                   13776: {
                   13777:     sub load_loncaparevs {
                   13778:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13779:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13780:                 while (my $configline=<$config>) {
                   13781:                     chomp($configline);
                   13782:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13783:                     $loncaparevs{$hostid}=$loncaparev;
                   13784:                 }
                   13785:                 close($config);
                   13786:             }
                   13787:         }
                   13788:     }
                   13789: }
                   13790: 
                   13791: # ----------------------------------------------------- Read serverhostID table
                   13792: {
                   13793:     sub load_serverhomeIDs {
                   13794:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13795:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13796:                 while (my $configline=<$config>) {
                   13797:                     chomp($configline);
                   13798:                     my ($name,$id)=split(/:/,$configline);
                   13799:                     $serverhomeIDs{$name}=$id;
                   13800:                 }
                   13801:                 close($config);
                   13802:             }
                   13803:         }
                   13804:     }
                   13805: }
                   13806: 
                   13807: 
1.862     albertel 13808: BEGIN {
                   13809: 
                   13810: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13811:     unless ($readit) {
                   13812: {
                   13813:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13814:     %perlvar = (%perlvar,%{$configvars});
                   13815: }
                   13816: 
                   13817: 
1.1       albertel 13818: # ------------------------------------------------------ Read spare server file
                   13819: {
1.1172.2.96  raeburn  13820:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13821: 
                   13822:     while (my $configline=<$config>) {
                   13823:        chomp($configline);
1.284     matthew  13824:        if ($configline) {
1.784     albertel 13825: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13826: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13827: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13828:        }
                   13829:     }
1.448     albertel 13830:     close($config);
1.1       albertel 13831: }
1.11      www      13832: # ------------------------------------------------------------ Read permissions
                   13833: {
1.1172.2.96  raeburn  13834:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13835: 
                   13836:     while (my $configline=<$config>) {
1.448     albertel 13837: 	chomp($configline);
                   13838: 	if ($configline) {
                   13839: 	    my ($role,$perm)=split(/ /,$configline);
                   13840: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13841: 	}
1.11      www      13842:     }
1.448     albertel 13843:     close($config);
1.11      www      13844: }
                   13845: 
                   13846: # -------------------------------------------- Read plain texts for permissions
                   13847: {
1.1172.2.96  raeburn  13848:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13849: 
                   13850:     while (my $configline=<$config>) {
1.448     albertel 13851: 	chomp($configline);
                   13852: 	if ($configline) {
1.742     raeburn  13853: 	    my ($short,@plain)=split(/:/,$configline);
                   13854:             %{$prp{$short}} = ();
                   13855: 	    if (@plain > 0) {
                   13856:                 $prp{$short}{'std'} = $plain[0];
                   13857:                 for (my $i=1; $i<@plain; $i++) {
                   13858:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13859:                 }
                   13860:             }
1.448     albertel 13861: 	}
1.135     www      13862:     }
1.448     albertel 13863:     close($config);
1.135     www      13864: }
                   13865: 
                   13866: # ---------------------------------------------------------- Read package table
                   13867: {
1.1172.2.96  raeburn  13868:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13869: 
                   13870:     while (my $configline=<$config>) {
1.483     albertel 13871: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13872: 	chomp($configline);
                   13873: 	my ($short,$plain)=split(/:/,$configline);
                   13874: 	my ($pack,$name)=split(/\&/,$short);
                   13875: 	if ($plain ne '') {
                   13876: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13877: 	    $packagetab{$short}=$plain; 
                   13878: 	}
1.11      www      13879:     }
1.448     albertel 13880:     close($config);
1.329     matthew  13881: }
                   13882: 
1.1172.2.27  raeburn  13883: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13884: 
1.1172.2.27  raeburn  13885: &load_loncaparevs();
                   13886: 
                   13887: # ------------------------------------------------------- Read serverhostID table
                   13888: 
                   13889: &load_serverhomeIDs();
1.1074    raeburn  13890: 
1.1172.2.27  raeburn  13891: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13892: {
                   13893:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13894:     if (-e $file) {
                   13895:         my $parser = HTML::LCParser->new($file);
                   13896:         while (my $token = $parser->get_token()) {
                   13897:             if ($token->[0] eq 'S') {
                   13898:                 my $item = $token->[1];
                   13899:                 my $name = $token->[2]{'name'};
                   13900:                 my $value = $token->[2]{'value'};
                   13901:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13902:                     my $release = $parser->get_text();
                   13903:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13904:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13905:                 }
                   13906:             }
                   13907:         }
                   13908:     }
1.1073    raeburn  13909: }
                   13910: 
1.1138    raeburn  13911: # ---------------------------------------------------------- Read managers table
                   13912: {
                   13913:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13914:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13915:             while (my $configline=<$config>) {
                   13916:                 chomp($configline);
                   13917:                 next if ($configline =~ /^\#/);
                   13918:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13919:                     $managerstab{$configline} = 1;
                   13920:                 }
                   13921:             }
                   13922:             close($config);
                   13923:         }
                   13924:     }
                   13925: }
                   13926: 
1.329     matthew  13927: # ------------- set up temporary directory
                   13928: {
1.1117    foxr     13929:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13930: 
1.11      www      13931: }
                   13932: 
1.1172.2.104  raeburn  13933: # ------------- set default texengine (domain default overrides this)
                   13934: {
                   13935:     $deftex = LONCAPA::texengine();
                   13936: }
                   13937: 
1.1172.2.114! raeburn  13938: # ------------- set default minimum length for passwords for internal auth users
        !          13939: {
        !          13940:     $passwdmin = LONCAPA::passwd_min();
        !          13941: }
        !          13942: 
1.794     albertel 13943: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13944: 				'compress_threshold'=> 20_000,
                   13945:  			        });
1.185     www      13946: 
1.281     www      13947: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13948: $dumpcount=0;
1.958     www      13949: $locknum=0;
1.22      www      13950: 
1.163     harris41 13951: &logtouch();
1.672     albertel 13952: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13953: $readit=1;
1.564     albertel 13954:     {
                   13955: 	use integer;
                   13956: 	my $test=(2**32)+1;
1.568     albertel 13957: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13958: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13959:     }
1.195     www      13960: }
1.1       albertel 13961: }
1.179     www      13962: 
1.1       albertel 13963: 1;
1.191     harris41 13964: __END__
                   13965: 
1.243     albertel 13966: =pod
                   13967: 
1.191     harris41 13968: =head1 NAME
                   13969: 
1.243     albertel 13970: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13971: 
                   13972: =head1 SYNOPSIS
                   13973: 
1.243     albertel 13974: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13975: 
                   13976:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13977: 
1.243     albertel 13978: Common parameters:
                   13979: 
                   13980: =over 4
                   13981: 
                   13982: =item *
                   13983: 
                   13984: $uname : an internal username (if $cname expecting a course Id specifically)
                   13985: 
                   13986: =item *
                   13987: 
                   13988: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13989: 
                   13990: =item *
                   13991: 
                   13992: $symb : a resource instance identifier
                   13993: 
                   13994: =item *
                   13995: 
                   13996: $namespace : the name of a .db file that contains the data needed or
                   13997: being set.
                   13998: 
                   13999: =back
                   14000: 
1.394     bowersj2 14001: =head1 OVERVIEW
1.191     harris41 14002: 
1.394     bowersj2 14003: lonnet provides subroutines which interact with the
                   14004: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14005: about classes, users, and resources.
1.243     albertel 14006: 
                   14007: For many of these objects you can also use this to store data about
                   14008: them or modify them in various ways.
1.191     harris41 14009: 
1.394     bowersj2 14010: =head2 Symbs
1.191     harris41 14011: 
1.394     bowersj2 14012: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14013: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14014: map, the resource number of the resource in the map, and the URL of
                   14015: the resource itself. The latter is somewhat redundant, but might help
                   14016: if maps change.
                   14017: 
                   14018: An example is
                   14019: 
                   14020:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14021: 
                   14022: The respective map entry is
                   14023: 
                   14024:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14025:   title="Problem 2">
                   14026:  </resource>
                   14027: 
                   14028: Symbs are used by the random number generator, as well as to store and
                   14029: restore data specific to a certain instance of for example a problem.
                   14030: 
                   14031: =head2 Storing And Retrieving Data
                   14032: 
                   14033: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14034: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14035: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14036: is is the non-critical message twin of cstore. These functions are for
                   14037: handlers to store a perl hash to a user's permanent data space in an
                   14038: easy manner, and to retrieve it again on another call. It is expected
                   14039: that a handler would use this once at the beginning to retrieve data,
                   14040: and then again once at the end to send only the new data back.
                   14041: 
                   14042: The data is stored in the user's data directory on the user's
                   14043: homeserver under the ID of the course.
                   14044: 
                   14045: The hash that is returned by restore will have all of the previous
                   14046: value for all of the elements of the hash.
                   14047: 
                   14048: Example:
                   14049: 
                   14050:  #creating a hash
                   14051:  my %hash;
                   14052:  $hash{'foo'}='bar';
                   14053: 
                   14054:  #storing it
                   14055:  &Apache::lonnet::cstore(\%hash);
                   14056: 
                   14057:  #changing a value
                   14058:  $hash{'foo'}='notbar';
                   14059: 
                   14060:  #adding a new value
                   14061:  $hash{'bar'}='foo';
                   14062:  &Apache::lonnet::cstore(\%hash);
                   14063: 
                   14064:  #retrieving the hash
                   14065:  my %history=&Apache::lonnet::restore();
                   14066: 
                   14067:  #print the hash
                   14068:  foreach my $key (sort(keys(%history))) {
                   14069:    print("\%history{$key} = $history{$key}");
                   14070:  }
                   14071: 
                   14072: Will print out:
1.191     harris41 14073: 
1.394     bowersj2 14074:  %history{1:foo} = bar
                   14075:  %history{1:keys} = foo:timestamp
                   14076:  %history{1:timestamp} = 990455579
                   14077:  %history{2:bar} = foo
                   14078:  %history{2:foo} = notbar
                   14079:  %history{2:keys} = foo:bar:timestamp
                   14080:  %history{2:timestamp} = 990455580
                   14081:  %history{bar} = foo
                   14082:  %history{foo} = notbar
                   14083:  %history{timestamp} = 990455580
                   14084:  %history{version} = 2
                   14085: 
                   14086: Note that the special hash entries C<keys>, C<version> and
                   14087: C<timestamp> were added to the hash. C<version> will be equal to the
                   14088: total number of versions of the data that have been stored. The
                   14089: C<timestamp> attribute will be the UNIX time the hash was
                   14090: stored. C<keys> is available in every historical section to list which
                   14091: keys were added or changed at a specific historical revision of a
                   14092: hash.
                   14093: 
                   14094: B<Warning>: do not store the hash that restore returns directly. This
                   14095: will cause a mess since it will restore the historical keys as if the
                   14096: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14097: 
1.394     bowersj2 14098: Calling convention:
1.191     harris41 14099: 
1.1172.2.27  raeburn  14100:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14101:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14102: 
1.394     bowersj2 14103: For more detailed information, see lonnet specific documentation.
1.191     harris41 14104: 
1.394     bowersj2 14105: =head1 RETURN MESSAGES
1.191     harris41 14106: 
1.394     bowersj2 14107: =over 4
1.191     harris41 14108: 
1.394     bowersj2 14109: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14110: 
1.394     bowersj2 14111: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14112: when the connection is brought back up
1.191     harris41 14113: 
1.394     bowersj2 14114: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14115: for later delivery
1.191     harris41 14116: 
1.967     bisitz   14117: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14118: 
1.394     bowersj2 14119: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14120: that was requested
1.191     harris41 14121: 
1.243     albertel 14122: =back
1.191     harris41 14123: 
1.243     albertel 14124: =head1 PUBLIC SUBROUTINES
1.191     harris41 14125: 
1.243     albertel 14126: =head2 Session Environment Functions
1.191     harris41 14127: 
1.243     albertel 14128: =over 4
1.191     harris41 14129: 
1.394     bowersj2 14130: =item * 
                   14131: X<appenv()>
1.949     raeburn  14132: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14133: the user envirnoment file, and will be restored for each access this
1.620     albertel 14134: user makes during this session, also modifies the %env for the current
1.949     raeburn  14135: process. Optional rolesarrayref - if defined contains a reference to an array
                   14136: of roles which are exempt from the restriction on modifying user.role entries 
                   14137: in the user's environment.db and in %env.    
1.191     harris41 14138: 
                   14139: =item *
1.394     bowersj2 14140: X<delenv()>
1.987     raeburn  14141: B<delenv($delthis,$regexp)>: removes all items from the session
                   14142: environment file that begin with $delthis. If the 
                   14143: optional second arg - $regexp - is true, $delthis is treated as a 
                   14144: regular expression, otherwise \Q$delthis\E is used. 
                   14145: The values are also deleted from the current processes %env.
1.191     harris41 14146: 
1.795     albertel 14147: =item * get_env_multiple($name) 
                   14148: 
                   14149: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14150: values may be defined and end up as an array ref.
                   14151: 
                   14152: returns an array of values
                   14153: 
1.243     albertel 14154: =back
                   14155: 
                   14156: =head2 User Information
1.191     harris41 14157: 
1.243     albertel 14158: =over 4
1.191     harris41 14159: 
                   14160: =item *
1.394     bowersj2 14161: X<queryauthenticate()>
                   14162: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14163: authentication scheme
                   14164: 
                   14165: =item *
1.394     bowersj2 14166: X<authenticate()>
1.1073    raeburn  14167: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14168: authenticate user from domain's lib servers (first use the current
                   14169: one). C<$upass> should be the users password.
1.1073    raeburn  14170: $checkdefauth is optional (value is 1 if a check should be made to
                   14171:    authenticate user using default authentication method, and allow
                   14172:    account creation if username does not have account in the domain).
                   14173: $clientcancheckhost is optional (value is 1 if checking whether the
                   14174:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14175: 
                   14176: =item *
1.394     bowersj2 14177: X<homeserver()>
                   14178: B<homeserver($uname,$udom)>: find the server which has
                   14179: the user's directory and files (there must be only one), this caches
                   14180: the answer, and also caches if there is a borken connection.
1.191     harris41 14181: 
                   14182: =item *
1.394     bowersj2 14183: X<idget()>
                   14184: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14185: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14186: username, and only 1 username per ID in a specific domain) (returns
                   14187: hash: id=>name,id=>name)
1.191     harris41 14188: 
                   14189: =item *
1.394     bowersj2 14190: X<idrget()>
                   14191: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14192: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14193: 
                   14194: =item *
1.394     bowersj2 14195: X<idput()>
                   14196: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14197: 
                   14198: =item *
1.394     bowersj2 14199: X<rolesinit()>
1.1169    droeschl 14200: B<rolesinit($udom,$username)>: get user privileges.
                   14201: returns user role, first access and timer interval hashes
1.243     albertel 14202: 
                   14203: =item *
1.1171    droeschl 14204: X<privileged()>
                   14205: B<privileged($username,$domain)>: returns a true if user has a
                   14206: privileged and active role (i.e. su or dc), false otherwise.
                   14207: 
                   14208: =item *
1.551     albertel 14209: X<getsection()>
                   14210: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14211: course $cname, return section name/number or '' for "not in course"
                   14212: and '-1' for "no section"
                   14213: 
                   14214: =item *
1.394     bowersj2 14215: X<userenvironment()>
                   14216: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14217: passed in @what from the requested user's environment, returns a hash
                   14218: 
1.858     raeburn  14219: =item * 
                   14220: X<userlog_query()>
1.859     albertel 14221: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14222: activity.log file. %filters defines filters applied when parsing the
                   14223: log file. These can be start or end timestamps, or the type of action
                   14224: - log to look for Login or Logout events, check for Checkin or
                   14225: Checkout, role for role selection. The response is in the form
                   14226: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14227: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14228: 
1.243     albertel 14229: =back
                   14230: 
                   14231: =head2 User Roles
                   14232: 
                   14233: =over 4
                   14234: 
                   14235: =item *
                   14236: 
1.1172.2.65  raeburn  14237: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14238: returns codes for allowed actions.
                   14239: 
                   14240: The first argument is required, all others are optional.
                   14241: 
                   14242: $priv is the privilege being checked.
                   14243: $uri contains additional information about what is being checked for access (e.g.,
                   14244: URL, course ID etc.).
                   14245: $symb is the unique resource instance identifier in a course; if needed,
                   14246: but not provided, it will be retrieved via a call to &symbread().
                   14247: $role is the role for which a priv is being checked (only used if priv is evb).
                   14248: $clientip is the user's IP address (only used when checking for access to portfolio
                   14249: files).
                   14250: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14251: prevents recursive calls to &allowed.
                   14252: 
1.243     albertel 14253:  F: full access
                   14254:  U,I,K: authentication modes (cxx only)
                   14255:  '': forbidden
                   14256:  1: user needs to choose course
                   14257:  2: browse allowed
1.766     albertel 14258:  A: passphrase authentication needed
1.1172.2.65  raeburn  14259:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14260: 
                   14261: =item *
                   14262: 
1.1172.2.13  raeburn  14263: constructaccess($url,$setpriv) : check for access to construction space URL
                   14264: 
                   14265: See if the owner domain and name in the URL match those in the
                   14266: expected environment.  If so, return three element list
                   14267: ($ownername,$ownerdomain,$ownerhome).
                   14268: 
                   14269: Otherwise return the null string.
                   14270: 
                   14271: If second argument 'setpriv' is true, it assigns the privileges,
                   14272: and returns the same three element list, unless the owner has
                   14273: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14274: in which case the null string is returned.
                   14275: 
                   14276: =item *
                   14277: 
1.1172.2.84  raeburn  14278: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14279: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14280: for system, domain, and course level. $uname and $udom are optional (current
                   14281: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14282: 
                   14283: =item *
                   14284: 
1.988     raeburn  14285: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14286: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14287: $type is Course (default) or Community.
1.988     raeburn  14288: If $forcedefault evaluates to true, text returned will be default 
                   14289: text for $type. Otherwise, if this is a course, the text returned 
                   14290: will be a custom name for the role (if defined in the course's 
                   14291: environment).  If no custom name is defined the default is returned.
                   14292:    
1.832     raeburn  14293: =item *
                   14294: 
1.1172.2.23  raeburn  14295: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14296: All arguments are optional. Returns a hash of a roles, either for
                   14297: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14298: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14299: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14300: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14301: For each key, value is set to colon-separated start and end times for
                   14302: the role.  If no username and domain are specified, will default to
1.934     raeburn  14303: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14304: of role statuses (active, future or previous), roles 
                   14305: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14306: to restrict the list of roles reported. If no array ref is 
                   14307: provided for types, will default to return only active roles.
1.834     albertel 14308: 
1.1172.2.13  raeburn  14309: =item *
                   14310: 
                   14311: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14312: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14313: 
                   14314: Additional optional arguments are: $type (if role checking is to be restricted
                   14315: to certain user status types -- previous (expired roles), active (currently
                   14316: available roles) or future (roles available in the future), and
                   14317: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14318: have active Domain Coordinator role in course's domain or in additional
                   14319: domains (specified in 'Domains to check for privileged users' in course
                   14320: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14321: 
                   14322: =item *
                   14323: 
                   14324: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14325: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14326: $possdomains and $possroles are optional array refs -- to domains to check and
                   14327: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14328: users' roles.db to check for a dc or su role in any domain. This can be
                   14329: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14330: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14331: this then allows &privileged_by_domain() to be used, which caches the identity
                   14332: of privileged users, eliminating the need for repeated calls to &dump().
                   14333: 
                   14334: =item *
                   14335: 
                   14336: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14337: where the outer hash keys are domains specified in the $possdomains array ref,
                   14338: next inner hash keys are privileged roles specified in the $roles array ref,
                   14339: and the innermost hash contains key = value pairs for username:domain = end:start
                   14340: for active or future "privileged" users with that role in that domain. To avoid
                   14341: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14342: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14343: 
1.243     albertel 14344: =back
                   14345: 
                   14346: =head2 User Modification
                   14347: 
                   14348: =over 4
                   14349: 
                   14350: =item *
                   14351: 
1.957     raeburn  14352: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14353: user for the level given by URL.  Optional start and end dates (leave empty
                   14354: string or zero for "no date")
1.191     harris41 14355: 
                   14356: =item *
                   14357: 
1.243     albertel 14358: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14359: change a users, password, possible return values are: ok,
                   14360: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14361: refused
1.191     harris41 14362: 
                   14363: =item *
                   14364: 
1.243     albertel 14365: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14366: 
                   14367: =item *
                   14368: 
1.1058    raeburn  14369: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14370:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14371: 
                   14372: will update user information (firstname,middlename,lastname,generation,
                   14373: permanentemail), and if forceid is true, student/employee ID also.
                   14374: A user's institutional affiliation(s) can also be updated.
                   14375: User information fields will not be overwritten with empty entries 
                   14376: unless the field is included in the $candelete array reference.
                   14377: This array is included when a single user is modified via "Manage Users",
                   14378: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14379: 
                   14380: =item *
                   14381: 
1.286     matthew  14382: modifystudent
                   14383: 
1.957     raeburn  14384: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14385: The course id is resolved based on the current user's environment.  
                   14386: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14387: associated with a course.
                   14388: 
1.297     matthew  14389: This call is essentially a wrapper for lonnet::modifyuser and
                   14390: lonnet::modify_student_enrollment
1.286     matthew  14391: 
                   14392: Inputs: 
                   14393: 
                   14394: =over 4
                   14395: 
1.957     raeburn  14396: =item B<$udom> Student's loncapa domain
1.286     matthew  14397: 
1.957     raeburn  14398: =item B<$uname> Student's loncapa login name
1.286     matthew  14399: 
1.964     bisitz   14400: =item B<$uid> Student/Employee ID
1.286     matthew  14401: 
1.957     raeburn  14402: =item B<$umode> Student's authentication mode
1.286     matthew  14403: 
1.957     raeburn  14404: =item B<$upass> Student's password
1.286     matthew  14405: 
1.957     raeburn  14406: =item B<$first> Student's first name
1.286     matthew  14407: 
1.957     raeburn  14408: =item B<$middle> Student's middle name
1.286     matthew  14409: 
1.957     raeburn  14410: =item B<$last> Student's last name
1.286     matthew  14411: 
1.957     raeburn  14412: =item B<$gene> Student's generation
1.286     matthew  14413: 
1.957     raeburn  14414: =item B<$usec> Student's section in course
1.286     matthew  14415: 
                   14416: =item B<$end> Unix time of the roles expiration
                   14417: 
                   14418: =item B<$start> Unix time of the roles start date
                   14419: 
                   14420: =item B<$forceid> If defined, allow $uid to be changed
                   14421: 
                   14422: =item B<$desiredhome> server to use as home server for student
                   14423: 
1.957     raeburn  14424: =item B<$email> Student's permanent e-mail address
                   14425: 
                   14426: =item B<$type> Type of enrollment (auto or manual)
                   14427: 
1.963     raeburn  14428: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14429: 
                   14430: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14431: 
1.963     raeburn  14432: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14433: 
1.963     raeburn  14434: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14435: 
1.1172.2.19  raeburn  14436: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14437: 
                   14438: =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  14439: 
1.286     matthew  14440: =back
1.297     matthew  14441: 
                   14442: =item *
                   14443: 
                   14444: modify_student_enrollment
                   14445: 
1.1172.2.31  raeburn  14446: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14447: 'role.request.course' must be defined for this function to proceed.
                   14448: 
                   14449: Inputs:
                   14450: 
                   14451: =over 4
                   14452: 
1.1172.2.31  raeburn  14453: =item $udom, student's domain
1.297     matthew  14454: 
1.1172.2.31  raeburn  14455: =item $uname, student's name
1.297     matthew  14456: 
1.1172.2.31  raeburn  14457: =item $uid, student's user id
1.297     matthew  14458: 
1.1172.2.31  raeburn  14459: =item $first, student's first name
1.297     matthew  14460: 
                   14461: =item $middle
                   14462: 
                   14463: =item $last
                   14464: 
                   14465: =item $gene
                   14466: 
                   14467: =item $usec
                   14468: 
                   14469: =item $end
                   14470: 
                   14471: =item $start
                   14472: 
1.957     raeburn  14473: =item $type
                   14474: 
                   14475: =item $locktype
                   14476: 
                   14477: =item $cid
                   14478: 
                   14479: =item $selfenroll
                   14480: 
                   14481: =item $context
                   14482: 
1.1172.2.19  raeburn  14483: =item $credits, number of credits student will earn from this class
                   14484: 
1.1172.2.76  raeburn  14485: =item $instsec, institutional course section code for student
                   14486: 
1.297     matthew  14487: =back
                   14488: 
1.191     harris41 14489: 
                   14490: =item *
                   14491: 
1.243     albertel 14492: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14493: custom role; give a custom role to a user for the level given by URL.  Specify
                   14494: name and domain of role author, and role name
1.191     harris41 14495: 
                   14496: =item *
                   14497: 
1.243     albertel 14498: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14499: 
                   14500: =item *
                   14501: 
1.243     albertel 14502: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14503: 
                   14504: =back
                   14505: 
                   14506: =head2 Course Infomation
                   14507: 
                   14508: =over 4
1.191     harris41 14509: 
                   14510: =item *
                   14511: 
1.1118    foxr     14512: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14513: specified course id, including all environment settings for the
                   14514: course, the description of the course will be in the hash under the
                   14515: key 'description'
1.191     harris41 14516: 
1.1118    foxr     14517: $options is an optional parameter that if supplied is a hash reference that controls
                   14518: what how this function works.  It has the following key/values:
                   14519: 
                   14520: =over 4
                   14521: 
                   14522: =item freshen_cache
                   14523: 
                   14524: If defined, and the environment cache for the course is valid, it is 
                   14525: returned in the returned hash.
                   14526: 
                   14527: =item one_time
                   14528: 
                   14529: If defined, the last cache time is set to _now_
                   14530: 
                   14531: =item user
                   14532: 
                   14533: If defined, the supplied username is used instead of the current user.
                   14534: 
                   14535: 
                   14536: =back
                   14537: 
1.191     harris41 14538: =item *
                   14539: 
1.624     albertel 14540: resdata($name,$domain,$type,@which) : request for current parameter
                   14541: setting for a specific $type, where $type is either 'course' or 'user',
                   14542: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14543: answers for 10 minutes.
1.243     albertel 14544: 
1.877     foxr     14545: =item *
                   14546: 
                   14547: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14548: data base, returning a hash that is keyed by the resource name and has
                   14549: values that are the resource value.  I believe that the timestamps and
                   14550: versions are also returned.
                   14551: 
1.1172.2.31  raeburn  14552: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14553: supplemental content area. This routine caches the number of files for
                   14554: 10 minutes.
                   14555: 
1.243     albertel 14556: =back
                   14557: 
                   14558: =head2 Course Modification
                   14559: 
                   14560: =over 4
1.191     harris41 14561: 
                   14562: =item *
                   14563: 
1.243     albertel 14564: writecoursepref($courseid,%prefs) : write preferences (environment
                   14565: database) for a course
1.191     harris41 14566: 
                   14567: =item *
                   14568: 
1.1011    raeburn  14569: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14570: 
                   14571: =item *
                   14572: 
1.1038    raeburn  14573: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14574: 
1.1167    droeschl 14575: =item *
                   14576: 
                   14577: is_course($courseid), is_course($cdom, $cnum)
                   14578: 
                   14579: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14580: two component version $cdom, $cnum. It checks if the specified course exists.
                   14581: 
                   14582: Returns:
                   14583:     undef if the course doesn't exist, otherwise
                   14584:     in scalar context the combined courseid.
                   14585:     in list context the two components of the course identifier, domain and 
                   14586:     courseid.    
                   14587: 
1.243     albertel 14588: =back
                   14589: 
1.1172.2.109  raeburn  14590: =head2 Bubblesheet Configuration
                   14591: 
                   14592: =over 4
                   14593: 
                   14594: =item *
                   14595: 
                   14596: get_scantron_config($which)
                   14597: 
                   14598: $which - the name of the configuration to parse from the file.
                   14599: 
                   14600: Parses and returns the bubblesheet configuration line selected as a
                   14601: hash of configuration file fields.
                   14602: 
                   14603: 
                   14604: Returns:
                   14605:     If the named configuration is not in the file, an empty
                   14606:     hash is returned.
                   14607: 
                   14608:     a hash with the fields
                   14609:       name         - internal name for the this configuration setup
                   14610:       description  - text to display to operator that describes this config
                   14611:       CODElocation - if 0 or the string 'none'
                   14612:                           - no CODE exists for this config
                   14613:                      if -1 || the string 'letter'
                   14614:                           - a CODE exists for this config and is
                   14615:                             a string of letters
                   14616:                      Unsupported value (but planned for future support)
                   14617:                           if a positive integer
                   14618:                                - The CODE exists as the first n items from
                   14619:                                  the question section of the form
                   14620:                           if the string 'number'
                   14621:                                - The CODE exists for this config and is
                   14622:                                  a string of numbers
                   14623:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14624:                      the CODE starts
                   14625:       CODElength  - length of the CODE
                   14626:       IDstart     - column where the student/employee ID starts
                   14627:       IDlength    - length of the student/employee ID info
                   14628:       Qstart      - column where the information from the bubbled
                   14629:                     'questions' start
                   14630:       Qlength     - number of columns comprising a single bubble line from
                   14631:                     the sheet. (usually either 1 or 10)
                   14632:       Qon         - either a single character representing the character used
                   14633:                     to signal a bubble was chosen in the positional setup, or
                   14634:                     the string 'letter' if the letter of the chosen bubble is
                   14635:                     in the final, or 'number' if a number representing the
                   14636:                     chosen bubble is in the file (1->A 0->J)
                   14637:       Qoff        - the character used to represent that a bubble was
                   14638:                     left blank
                   14639:       PaperID     - if the scanning process generates a unique number for each
                   14640:                     sheet scanned the column that this ID number starts in
                   14641:       PaperIDlength - number of columns that comprise the unique ID number
                   14642:                       for the sheet of paper
                   14643:       FirstName   - column that the first name starts in
                   14644:       FirstNameLength - number of columns that the first name spans
                   14645:       LastName    - column that the last name starts in
                   14646:       LastNameLength - number of columns that the last name spans
                   14647:       BubblesPerRow - number of bubbles available in each row used to
                   14648:                       bubble an answer. (If not specified, 10 assumed).
                   14649: 
                   14650: 
                   14651: =item *
                   14652: 
                   14653: get_scantronformat_file($cdom)
                   14654: 
                   14655: $cdom - the course's domain (optional); if not supplied, uses
                   14656: domain for current $env{'request.course.id'}.
                   14657: 
                   14658: Returns an array containing lines from the scantron format file for
                   14659: the domain of the course.
                   14660: 
                   14661: If a url for a custom.tab file is listed in domain's configuration.db,
                   14662: lines are from this file.
                   14663: 
                   14664: Otherwise, if a default.tab has been published in RES space by the
                   14665: domainconfig user, lines are from this file.
                   14666: 
                   14667: Otherwise, fall back to getting lines from the legacy file on the
                   14668: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14669: 
                   14670: =back
                   14671: 
1.243     albertel 14672: =head2 Resource Subroutines
                   14673: 
                   14674: =over 4
1.191     harris41 14675: 
                   14676: =item *
                   14677: 
1.243     albertel 14678: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14679: 
                   14680: =item *
                   14681: 
1.243     albertel 14682: repcopy($filename) : subscribes to the requested file, and attempts to
                   14683: replicate from the owning library server, Might return
1.607     raeburn  14684: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14685: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14686: resource. Expects the local filesystem pathname
                   14687: (/home/httpd/html/res/....)
                   14688: 
                   14689: =back
                   14690: 
                   14691: =head2 Resource Information
                   14692: 
                   14693: =over 4
1.191     harris41 14694: 
                   14695: =item *
                   14696: 
1.1172.2.28  raeburn  14697: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14698: and returns the value of a variety of different possible values,
                   14699: $varname should be a request string, and the other parameters can be
                   14700: used to specify who and what one is asking about. Ordinarily, $cid 
                   14701: does not need to be specified, as it is retrived from 
                   14702: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14703: within lonuserstate::loadmap() when initializing a course, before
                   14704: $env{'request.course.id'} has been set, so it needs to be provided
                   14705: in that one case.
1.243     albertel 14706: 
                   14707: Possible values for $varname are environment.lastname (or other item
                   14708: from the envirnment hash), user.name (or someother aspect about the
                   14709: user), resource.0.maxtries (or some other part and parameter of a
                   14710: resource)
1.204     albertel 14711: 
                   14712: =item *
                   14713: 
1.243     albertel 14714: directcondval($number) : get current value of a condition; reads from a state
                   14715: string
1.204     albertel 14716: 
                   14717: =item *
                   14718: 
1.243     albertel 14719: condval($condidx) : value of condition index based on state
1.204     albertel 14720: 
                   14721: =item *
                   14722: 
1.243     albertel 14723: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14724: resource's metadata, $what should be either a specific key, or either
                   14725: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14726: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14727: 
                   14728: this function automatically caches all requests
1.191     harris41 14729: 
                   14730: =item *
                   14731: 
1.243     albertel 14732: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14733: network of library servers; returns file handle of where SQL and regex results
                   14734: will be stored for query
1.191     harris41 14735: 
                   14736: =item *
                   14737: 
1.1172.2.66  raeburn  14738: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14739: return symbolic list entry (all arguments optional).
                   14740: 
                   14741: Args: filename is the filename (including path) for the file for which a symb
                   14742: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14743: to check access status if more than one resource was found in the bighash
                   14744: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14745: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14746: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14747: cause possible symbs to be checked to determine if they are subject to content
                   14748: blocking, if so they will not be included as possible symbs; possibles is a
                   14749: ref to a hash, which, as a side effect, will be populated with all possible
                   14750: symbs (content blocking not tested).
                   14751: 
1.243     albertel 14752: returns the data handle
1.191     harris41 14753: 
                   14754: =item *
                   14755: 
1.1172.2.17  raeburn  14756: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14757: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14758: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14759: on failure, user must be in a course, as it assumes the existence of
                   14760: the course initial hash, and uses $env('request.course.id'}.  The third
                   14761: arg is an optional reference to a scalar.  If this arg is passed in the
                   14762: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14763: encrypted; otherwise it will be null.
1.243     albertel 14764: 
1.191     harris41 14765: =item *
                   14766: 
1.243     albertel 14767: symbclean($symb) : removes versions numbers from a symb, returns the
                   14768: cleaned symb
1.191     harris41 14769: 
                   14770: =item *
                   14771: 
1.243     albertel 14772: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14773: course map, user must be in a course for it to work.
1.191     harris41 14774: 
                   14775: =item *
                   14776: 
1.243     albertel 14777: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14778: 
                   14779: =item *
                   14780: 
1.243     albertel 14781: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14782: a random seed, all arguments are optional, if they aren't sent it uses the
                   14783: environment to derive them. Note: if symb isn't sent and it can't get one
                   14784: from &symbread it will use the current time as its return value
1.191     harris41 14785: 
                   14786: =item *
                   14787: 
1.243     albertel 14788: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14789: unfakeable, receipt
1.191     harris41 14790: 
                   14791: =item *
                   14792: 
1.620     albertel 14793: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14794: 
                   14795: =item *
                   14796: 
1.243     albertel 14797: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14798: 
                   14799: =item *
                   14800: 
1.243     albertel 14801: 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 14802: 
                   14803: =item *
                   14804: 
1.243     albertel 14805: 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 14806: 
                   14807: =item *
                   14808: 
1.243     albertel 14809: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14810: 
                   14811: =item *
                   14812: 
1.243     albertel 14813: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14814: forcing spreadsheet to reevaluate the resource scores next time.
                   14815: 
1.1172.2.13  raeburn  14816: =item *
                   14817: 
                   14818: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14819: when viewing in course context.
                   14820: 
                   14821:  input: six args -- filename (decluttered), course number, course domain,
                   14822:                     url, symb (if registered) and group (if this is a
                   14823:                     group item -- e.g., bulletin board, group page etc.).
                   14824: 
                   14825:  output: array of five scalars --
                   14826:          $cfile -- url for file editing if editable on current server
                   14827:          $home -- homeserver of resource (i.e., for author if published,
                   14828:                                           or course if uploaded.).
                   14829:          $switchserver --  1 if server switch will be needed.
                   14830:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14831:          $forceview -- 1 if icon/link should be to go to view mode
                   14832: 
                   14833: =item *
                   14834: 
                   14835: is_course_upload($file,$cnum,$cdom)
                   14836: 
                   14837: Used in course context to determine if current file was uploaded to
                   14838: the course (i.e., would be found in /userfiles/docs on the course's
                   14839: homeserver.
                   14840: 
                   14841:   input: 3 args -- filename (decluttered), course number and course domain.
                   14842:   output: boolean -- 1 if file was uploaded.
                   14843: 
1.243     albertel 14844: =back
                   14845: 
                   14846: =head2 Storing/Retreiving Data
                   14847: 
                   14848: =over 4
1.191     harris41 14849: 
                   14850: =item *
                   14851: 
1.1172.2.64  raeburn  14852: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14853: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14854: the remaining args aren't required and if they aren't passed or are '' they will
                   14855: be derived from the env (with the exception of $laststore, which is an
                   14856: optional arg used when a user's submission is stored in grading).
                   14857: $laststore is $version=$timestamp, where $version is the most recent version
                   14858: number retrieved for the corresponding $symb in the $namespace db file, and
                   14859: $timestamp is the timestamp for that transaction (UNIX time).
                   14860: $laststore is currently only passed when cstore() is called by
                   14861: structuretags::finalize_storage().
1.191     harris41 14862: 
                   14863: =item *
                   14864: 
1.1172.2.64  raeburn  14865: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14866: but uses critical subroutine
1.191     harris41 14867: 
                   14868: =item *
                   14869: 
1.243     albertel 14870: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14871: all args are optional
1.191     harris41 14872: 
                   14873: =item *
                   14874: 
1.717     albertel 14875: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14876: dumps the complete (or key matching regexp) namespace into a hash
                   14877: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14878: normally &store()ed into
                   14879: 
                   14880: $range should be either an integer '100' (give me the first 100
                   14881:                                            matching records)
                   14882:               or be  two integers sperated by a - with no spaces
                   14883:                  '30-50' (give me the 30th through the 50th matching
                   14884:                           records)
                   14885: 
                   14886: 
                   14887: =item *
                   14888: 
1.1172.2.59  raeburn  14889: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14890: replaces a &store() version of data with a replacement set of data
                   14891: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14892: reference. If $tolog is true, the transaction is logged in the courselog
                   14893: with an action=PUTSTORE.
1.717     albertel 14894: 
                   14895: =item *
                   14896: 
1.243     albertel 14897: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14898: works very similar to store/cstore, but all data is stored in a
                   14899: temporary location and can be reset using tmpreset, $storehash should
                   14900: be a hash reference, returns nothing on success
1.191     harris41 14901: 
                   14902: =item *
                   14903: 
1.243     albertel 14904: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14905: similar to restore, but all data is stored in a temporary location and
                   14906: can be reset using tmpreset. Returns a hash of values on success,
                   14907: error string otherwise.
1.191     harris41 14908: 
                   14909: =item *
                   14910: 
1.243     albertel 14911: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14912: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14913: 
                   14914: =item *
                   14915: 
1.243     albertel 14916: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14917: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14918: 
                   14919: =item *
                   14920: 
1.243     albertel 14921: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14922: namesp ($udom and $uname are optional)
1.191     harris41 14923: 
                   14924: =item *
                   14925: 
1.702     albertel 14926: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14927: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14928: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14929: 
1.702     albertel 14930: $range should be either an integer '100' (give me the first 100
                   14931:                                            matching records)
                   14932:               or be  two integers sperated by a - with no spaces
                   14933:                  '30-50' (give me the 30th through the 50th matching
                   14934:                           records)
1.449     matthew  14935: =item *
                   14936: 
                   14937: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14938: $store can be a scalar, an array reference, or if the amount to be 
                   14939: incremented is > 1, a hash reference.
                   14940: 
                   14941: ($udom and $uname are optional)
1.191     harris41 14942: 
                   14943: =item *
                   14944: 
1.243     albertel 14945: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14946: ($udom and $uname are optional)
1.191     harris41 14947: 
                   14948: =item *
                   14949: 
1.243     albertel 14950: cput($namespace,$storehash,$udom,$uname) : critical put
                   14951: ($udom and $uname are optional)
1.191     harris41 14952: 
                   14953: =item *
                   14954: 
1.748     albertel 14955: newput($namespace,$storehash,$udom,$uname) :
                   14956: 
                   14957: Attempts to store the items in the $storehash, but only if they don't
                   14958: currently exist, if this succeeds you can be certain that you have 
                   14959: successfully created a new key value pair in the $namespace db.
                   14960: 
                   14961: 
                   14962: Args:
                   14963:  $namespace: name of database to store values to
                   14964:  $storehash: hashref to store to the db
                   14965:  $udom: (optional) domain of user containing the db
                   14966:  $uname: (optional) name of user caontaining the db
                   14967: 
                   14968: Returns:
                   14969:  'ok' -> succeeded in storing all keys of $storehash
                   14970:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14971:                         least <key> already existed in the db (other
                   14972:                         requested keys may also already exist)
1.967     bisitz   14973:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14974:  'con_lost' -> unable to contact request server
                   14975:  'refused' -> action was not allowed by remote machine
                   14976: 
                   14977: 
                   14978: =item *
                   14979: 
1.243     albertel 14980: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14981: reference filled in from namesp (encrypts the return communication)
                   14982: ($udom and $uname are optional)
1.191     harris41 14983: 
                   14984: =item *
                   14985: 
1.243     albertel 14986: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14987: critical subroutine
                   14988: 
1.806     raeburn  14989: =item *
                   14990: 
1.860     raeburn  14991: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14992: array reference filled in from namespace found in domain level on either
                   14993: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14994: 
                   14995: =item *
                   14996: 
1.860     raeburn  14997: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14998: domain level either on specified domain server ($uhome) or primary domain 
                   14999: server ($udom and $uhome are optional)
1.806     raeburn  15000: 
1.943     raeburn  15001: =item * 
                   15002: 
1.1172.2.35  raeburn  15003: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15004: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15005: the target domain.
                   15006: 
                   15007: May also include additional key => value pairs for the following groups:
                   15008: 
                   15009: =over
                   15010: 
                   15011: =item
                   15012: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15013: 
                   15014: =over
                   15015: 
                   15016: =item defaultquota, authorquota
                   15017: 
                   15018: =back
                   15019: 
                   15020: =item
                   15021: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15022: portfolio for users).
                   15023: 
                   15024: =over
                   15025: 
                   15026: =item
                   15027: aboutme, blog, webdav, portfolio
                   15028: 
                   15029: =back
                   15030: 
                   15031: =item
                   15032: requestcourses: ability to request courses, and how requests are processed.
                   15033: 
                   15034: =over
                   15035: 
                   15036: =item
1.1172.2.37  raeburn  15037: official, unofficial, community, textbook
1.1172.2.35  raeburn  15038: 
                   15039: =back
                   15040: 
                   15041: =item
                   15042: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15043: 
                   15044: =over
                   15045: 
                   15046: =item
1.1172.2.44  raeburn  15047: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15048: 
                   15049: =back
                   15050: 
                   15051: =item
                   15052: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15053: for course's uploaded content.
                   15054: 
                   15055: =over
                   15056: 
                   15057: =item
1.1172.2.68  raeburn  15058: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15059: communityquota, textbookquota
1.1172.2.35  raeburn  15060: 
                   15061: =back
                   15062: 
                   15063: =item
                   15064: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15065: on your servers.
                   15066: 
                   15067: =over
                   15068: 
                   15069: =item
                   15070: remotesessions, hostedsessions
                   15071: 
                   15072: =back
                   15073: 
                   15074: =back
                   15075: 
                   15076: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15077: utility to create a configuration.db file on a domain's primary library server
                   15078: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15079: -- corresponding values are authentication type (internal, krb4, krb5,
                   15080: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15081: will be available. Values are retrieved from cache (if current), unless the
                   15082: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15083: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15084: 
                   15085: Typical usage:
1.943     raeburn  15086: 
1.1172.2.35  raeburn  15087: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15088: 
1.243     albertel 15089: =back
                   15090: 
                   15091: =head2 Network Status Functions
                   15092: 
                   15093: =over 4
1.191     harris41 15094: 
                   15095: =item *
                   15096: 
1.1137    raeburn  15097: dirlist() : return directory list based on URI (first arg).
                   15098: 
                   15099: Inputs: 1 required, 5 optional.
                   15100: 
                   15101: =over
                   15102: 
                   15103: =item 
                   15104: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15105: 
                   15106: =item
                   15107: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15108: 
                   15109: =item
                   15110: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15111: 
                   15112: =item
                   15113: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15114: 
                   15115: =item
                   15116: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15117: 
                   15118: =item 
                   15119: $alternateRoot - path to prepend in place of path from $uri.
                   15120: 
                   15121: =back
                   15122: 
                   15123: Returns: Array of up to two items.
                   15124: 
                   15125: =over
                   15126: 
                   15127: a reference to an array of files/subdirectories
                   15128: 
                   15129: =over
                   15130: 
                   15131: Each element in the array of files/subdirectories is a & separated list of
                   15132: item name and the result of running stat on the item.  If dirlist was requested
                   15133: for a file instead of a directory, the item name will be ''. For a directory 
                   15134: listing, if the item is a metadata file, the element will end &N&M 
                   15135: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15136: default copyright set (1).  
                   15137: 
                   15138: =back
                   15139: 
                   15140: a scalar containing error condition (if encountered).
                   15141: 
                   15142: =over
                   15143: 
                   15144: =item 
                   15145: no_host (no homeserver identified for $username:$domain).
                   15146: 
                   15147: =item 
                   15148: no_such_host (server contacted for listing not identified as valid host).
                   15149: 
                   15150: =item 
                   15151: con_lost (connection to remote server failed).
                   15152: 
                   15153: =item 
                   15154: refused (invalid $username:$domain received on lond side).
                   15155: 
                   15156: =item 
                   15157: no_such_dir (directory at specified path on lond side does not exist). 
                   15158: 
                   15159: =item 
                   15160: empty (directory at specified path on lond side is empty).
                   15161: 
                   15162: =over
                   15163: 
                   15164: This is currently not encountered because the &ls3, &ls2, 
                   15165: &ls (_handler) routines on the lond side do not filter out
                   15166: . and .. from a directory listing. 
                   15167: 
                   15168: =back
                   15169: 
                   15170: =back
                   15171: 
                   15172: =back
1.191     harris41 15173: 
                   15174: =item *
                   15175: 
1.243     albertel 15176: spareserver() : find server with least workload from spare.tab
                   15177: 
1.986     foxr     15178: 
                   15179: =item *
                   15180: 
                   15181: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15182: if there is no corresponding loncapa host.
                   15183: 
1.243     albertel 15184: =back
                   15185: 
1.986     foxr     15186: 
1.243     albertel 15187: =head2 Apache Request
                   15188: 
                   15189: =over 4
1.191     harris41 15190: 
                   15191: =item *
                   15192: 
1.243     albertel 15193: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15194: localhost, posts hash
                   15195: 
                   15196: =back
                   15197: 
                   15198: =head2 Data to String to Data
                   15199: 
                   15200: =over 4
1.191     harris41 15201: 
                   15202: =item *
                   15203: 
1.243     albertel 15204: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15205: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15206: 
                   15207: =item *
                   15208: 
1.243     albertel 15209: hashref2str($hashref) : convert a hashref into a string complete with
                   15210: escaping and '=' and '&' separators, supports elements that are
                   15211: arrayrefs and hashrefs
1.191     harris41 15212: 
                   15213: =item *
                   15214: 
1.243     albertel 15215: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15216: with escaping and '&' separators, supports elements that are arrayrefs
                   15217: and hashrefs
1.191     harris41 15218: 
                   15219: =item *
                   15220: 
1.243     albertel 15221: str2hash($string) : convert string to hash using unescaping and
                   15222: splitting on '=' and '&', supports elements that are arrayrefs and
                   15223: hashrefs
1.191     harris41 15224: 
                   15225: =item *
                   15226: 
1.243     albertel 15227: str2array($string) : convert string to hash using unescaping and
                   15228: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15229: 
                   15230: =back
                   15231: 
                   15232: =head2 Logging Routines
                   15233: 
                   15234: 
                   15235: These routines allow one to make log messages in the lonnet.log and
                   15236: lonnet.perm logfiles.
1.191     harris41 15237: 
1.1119    foxr     15238: =over 4
                   15239: 
1.191     harris41 15240: =item *
                   15241: 
1.243     albertel 15242: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15243: 
                   15244: =item *
                   15245: 
1.243     albertel 15246: logthis() : append message to the normal lonnet.log file, it gets
                   15247: preiodically rolled over and deleted.
1.191     harris41 15248: 
                   15249: =item *
                   15250: 
1.243     albertel 15251: logperm() : append a permanent message to lonnet.perm.log, this log
                   15252: file never gets deleted by any automated portion of the system, only
                   15253: messages of critical importance should go in here.
                   15254: 
1.1119    foxr     15255: 
1.243     albertel 15256: =back
                   15257: 
                   15258: =head2 General File Helper Routines
                   15259: 
                   15260: =over 4
1.191     harris41 15261: 
                   15262: =item *
                   15263: 
1.481     raeburn  15264: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15265: (a) files in /uploaded
                   15266:   (i) If a local copy of the file exists - 
                   15267:       compares modification date of local copy with last-modified date for 
                   15268:       definitive version stored on home server for course. If local copy is 
                   15269:       stale, requests a new version from the home server and stores it. 
                   15270:       If the original has been removed from the home server, then local copy 
                   15271:       is unlinked.
                   15272:   (ii) If local copy does not exist -
                   15273:       requests the file from the home server and stores it. 
                   15274:   
                   15275:   If $caller is 'uploadrep':  
                   15276:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15277:     for request for files originally uploaded via DOCS. 
                   15278:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15279:   
                   15280:   Otherwise:
                   15281:      This indicates a call from the content generation phase of the request.
                   15282:      -  returns the entire contents of the file or -1.
                   15283:      
                   15284: (b) files in /res
                   15285:    - returns the entire contents of a file or -1; 
                   15286:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15287: 
1.712     albertel 15288: 
                   15289: =item *
                   15290: 
                   15291: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15292:                   reference
                   15293: 
                   15294: returns either a stat() list of data about the file or an empty list
                   15295: if the file doesn't exist or couldn't find out about it (connection
                   15296: problems or user unknown)
                   15297: 
1.191     harris41 15298: =item *
                   15299: 
1.243     albertel 15300: filelocation($dir,$file) : returns file system location of a file
                   15301: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15302: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15303: and a file of ../bob will become /a/bob)
1.191     harris41 15304: 
                   15305: =item *
                   15306: 
                   15307: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15308: filelocation except for hrefs
                   15309: 
                   15310: =item *
                   15311: 
1.1172.2.49  raeburn  15312: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15313: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15314: 
1.243     albertel 15315: =back
                   15316: 
1.608     albertel 15317: =head2 Usererfile file routines (/uploaded*)
                   15318: 
                   15319: =over 4
                   15320: 
                   15321: =item *
                   15322: 
                   15323: userfileupload(): main rotine for putting a file in a user or course's
                   15324:                   filespace, arguments are,
                   15325: 
1.620     albertel 15326:  formname - required - this is the name of the element in $env where the
1.608     albertel 15327:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15328:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15329:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15330:  context - if coursedoc, store the file in the course of the active role
                   15331:              of the current user; 
                   15332:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15333:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15334:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15335:          if undefined, it will be placed in "unknown"
                   15336: 
                   15337:  (This routine calls clean_filename() to remove any dangerous
                   15338:  characters from the filename, and then calls finuserfileupload() to
                   15339:  complete the transaction)
                   15340: 
                   15341:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15342:  and /adm/notfound.html if unsuccessful
                   15343: 
                   15344: =item *
                   15345: 
                   15346: clean_filename(): routine for cleaing a filename up for storage in
                   15347:                  userfile space, argument is:
                   15348: 
                   15349:  filename - proposed filename
                   15350: 
                   15351: returns: the new clean filename
                   15352: 
                   15353: =item *
                   15354: 
1.1090    raeburn  15355: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15356: userspace, probably shouldn't be called directly
                   15357: 
                   15358:   docuname: username or courseid of destination for the file
                   15359:   docudom: domain of user/course of destination for the file
                   15360:   formname: same as for userfileupload()
1.1090    raeburn  15361:   fname: filename (including subdirectories) for the file
                   15362:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15363:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15364:   allfiles: reference to hash used to store objects found by parser
                   15365:   codebase: reference to hash used for codebases of java objects found by parser
                   15366:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15367:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15368:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15369:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15370:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15371:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15372:   mimetype: reference to scalar to accommodate mime type determined
                   15373:             from File::MMagic if $parser = parse.
1.608     albertel 15374: 
                   15375:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15376:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15377:  was 'overwrite').
                   15378:  
1.608     albertel 15379: 
                   15380: =item *
                   15381: 
                   15382: renameuserfile(): renames an existing userfile to a new name
                   15383: 
                   15384:   Args:
                   15385:    docuname: username or courseid of destination for the file
                   15386:    docudom: domain of user/course of destination for the file
                   15387:    old: current file name (including any subdirs under userfiles)
                   15388:    new: desired file name (including any subdirs under userfiles)
                   15389: 
                   15390: =item *
                   15391: 
                   15392: mkdiruserfile(): creates a directory is a userfiles dir
                   15393: 
                   15394:   Args:
                   15395:    docuname: username or courseid of destination for the file
                   15396:    docudom: domain of user/course of destination for the file
                   15397:    dir: dir to create (including any subdirs under userfiles)
                   15398: 
                   15399: =item *
                   15400: 
                   15401: removeuserfile(): removes a file that exists in userfiles
                   15402: 
                   15403:   Args:
                   15404:    docuname: username or courseid of destination for the file
                   15405:    docudom: domain of user/course of destination for the file
                   15406:    fname: filname to delete (including any subdirs under userfiles)
                   15407: 
                   15408: =item *
                   15409: 
                   15410: removeuploadedurl(): convience function for removeuserfile()
                   15411: 
                   15412:   Args:
                   15413:    url:  a full /uploaded/... url to delete
                   15414: 
1.747     albertel 15415: =item * 
                   15416: 
                   15417: get_portfile_permissions():
                   15418:   Args:
                   15419:     domain: domain of user or course contain the portfolio files
                   15420:     user: name of user or num of course contain the portfolio files
                   15421:   Returns:
                   15422:     hashref of a dump of the proper file_permissions.db
                   15423:    
                   15424: 
                   15425: =item * 
                   15426: 
                   15427: get_access_controls():
                   15428: 
                   15429: Args:
                   15430:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15431:   group: (optional) the group you want the files associated with
                   15432:   file: (optional) the file you want access info on
                   15433: 
                   15434: Returns:
1.749     raeburn  15435:     a hash (keys are file names) of hashes containing
                   15436:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15437:         values are XML containing access control settings (see below) 
1.747     albertel 15438: 
                   15439: Internal notes:
                   15440: 
1.749     raeburn  15441:  access controls are stored in file_permissions.db as key=value pairs.
                   15442:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15443:         where scope -> public,guest,course,group,domains or users.
                   15444:               end -> UNIX time for end of access (0 -> no end date)
                   15445:               start -> UNIX time for start of access
                   15446: 
                   15447:     value -> XML description of access control
                   15448:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15449:             <start></start>
                   15450:             <end></end>
                   15451: 
                   15452:             <password></password>  for scope type = guest
                   15453: 
                   15454:             <domain></domain>     for scope type = course or group
                   15455:             <number></number>
                   15456:             <roles id="">
                   15457:              <role></role>
                   15458:              <access></access>
                   15459:              <section></section>
                   15460:              <group></group>
                   15461:             </roles>
                   15462: 
                   15463:             <dom></dom>         for scope type = domains
                   15464: 
                   15465:             <users>             for scope type = users
                   15466:              <user>
                   15467:               <uname></uname>
                   15468:               <udom></udom>
                   15469:              </user>
                   15470:             </users>
                   15471:            </scope> 
                   15472:               
                   15473:  Access data is also aggregated for each file in an additional key=value pair:
                   15474:  key -> path to file/file_name\0accesscontrol 
                   15475:  value -> reference to hash
                   15476:           hash contains key = value pairs
                   15477:           where key = uniqueID:scope_end_start
                   15478:                 value = UNIX time record was last updated
                   15479: 
                   15480:           Used to improve speed of look-ups of access controls for each file.  
                   15481:  
                   15482:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15483: 
1.1172.2.13  raeburn  15484: =item *
                   15485: 
1.749     raeburn  15486: modify_access_controls():
                   15487: 
                   15488: Modifies access controls for a portfolio file
                   15489: Args
                   15490: 1. file name
                   15491: 2. reference to hash of required changes,
                   15492: 3. domain
                   15493: 4. username
                   15494:   where domain,username are the domain of the portfolio owner 
                   15495:   (either a user or a course) 
                   15496: 
                   15497: Returns:
                   15498: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15499: 2. result of deletions ('ok' or 'error', with error message).
                   15500: 3. reference to hash of any new or updated access controls.
                   15501: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15502:    key = integer (inbound ID)
1.1172.2.13  raeburn  15503:    value = uniqueID
                   15504: 
                   15505: =item *
                   15506: 
                   15507: get_timebased_id():
                   15508: 
                   15509: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15510: course via the Course Editor (e.g., folders, composite pages,
                   15511: group bulletin boards).
                   15512: 
                   15513: Args: (first three required; six others optional)
                   15514: 
                   15515: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15516:    docssequence, or name of group
                   15517: 
                   15518: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15519:    e.g., num, boardids
                   15520: 
                   15521: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15522:    file will be named nohist_namespace.db
                   15523: 
                   15524: 4. cdom: domain of course; default is current course domain from %env
                   15525: 
                   15526: 5. cnum: course number; default is current course number from %env
                   15527: 
                   15528: 6. idtype: set to concat if an additional digit is to be appended to the
                   15529:    unix timestamp to form the suffix, if the plain timestamp is already
                   15530:    in use.  Default is to not do this, but simply increment the unix
                   15531:    timestamp by 1 until a unique key is obtained.
                   15532: 
                   15533: 7. who: holder of locking key; defaults to user:domain for user.
                   15534: 
                   15535: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15536:    retrying); default is 3.
                   15537: 
                   15538: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15539: 
                   15540: Returns:
                   15541: 
                   15542: 1. suffix obtained (numeric)
                   15543: 
                   15544: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15545: 
                   15546: 3. error: contains (localized) error message if an error occurred.
                   15547: 
1.747     albertel 15548: 
1.608     albertel 15549: =back
                   15550: 
1.243     albertel 15551: =head2 HTTP Helper Routines
                   15552: 
                   15553: =over 4
                   15554: 
1.191     harris41 15555: =item *
                   15556: 
                   15557: escape() : unpack non-word characters into CGI-compatible hex codes
                   15558: 
                   15559: =item *
                   15560: 
                   15561: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15562: 
1.243     albertel 15563: =back
                   15564: 
                   15565: =head1 PRIVATE SUBROUTINES
                   15566: 
                   15567: =head2 Underlying communication routines (Shouldn't call)
                   15568: 
                   15569: =over 4
                   15570: 
                   15571: =item *
                   15572: 
                   15573: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15574: 
                   15575: =item *
                   15576: 
                   15577: reply() : uses subreply to send a message to remote machine, logs all failures
                   15578: 
                   15579: =item *
                   15580: 
                   15581: critical() : passes a critical message to another server; if cannot
                   15582: get through then place message in connection buffer directory and
                   15583: returns con_delayed, if incapable of saving message, returns
                   15584: con_failed
                   15585: 
                   15586: =item *
                   15587: 
                   15588: reconlonc() : tries to reconnect lonc client processes.
                   15589: 
                   15590: =back
                   15591: 
                   15592: =head2 Resource Access Logging
                   15593: 
                   15594: =over 4
                   15595: 
                   15596: =item *
                   15597: 
                   15598: flushcourselogs() : flush (save) buffer logs and access logs
                   15599: 
                   15600: =item *
                   15601: 
                   15602: courselog($what) : save message for course in hash
                   15603: 
                   15604: =item *
                   15605: 
                   15606: courseacclog($what) : save message for course using &courselog().  Perform
                   15607: special processing for specific resource types (problems, exams, quizzes, etc).
                   15608: 
1.191     harris41 15609: =item *
                   15610: 
                   15611: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15612: as a PerlChildExitHandler
1.243     albertel 15613: 
                   15614: =back
                   15615: 
                   15616: =head2 Other
                   15617: 
                   15618: =over 4
                   15619: 
                   15620: =item *
                   15621: 
                   15622: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15623: 
                   15624: =back
                   15625: 
                   15626: =cut
1.877     foxr     15627: 

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