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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.117 2020/01/17 04:52:33 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.1172.2.116  raeburn  1988:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   1989:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  1990:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  1991:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   1992:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   1993:                     (($major == 2) && ($minor < 11)) ||
                   1994:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   1995:                     return;
                   1996:                 }
                   1997:             }
                   1998:         }
1.904     albertel 1999: 	my $queryid=&reply("querysend:instdirsearch:".
                   2000: 			   &escape($srch->{'srchby'}).':'.
                   2001: 			   &escape($srch->{'srchterm'}).':'.
                   2002: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2003: 	my $host=&hostname($homeserver);
                   2004: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2005: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2006: 	    return;
                   2007: 	}
                   2008: 	my $response = &get_query_reply($queryid);
                   2009: 	my $maxtries = 5;
                   2010: 	my $tries = 1;
                   2011: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2012: 	    $response = &get_query_reply($queryid);
                   2013: 	    $tries ++;
                   2014: 	}
                   2015: 
                   2016:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2017:             if ($response eq 'unavailable') {
                   2018:                 $outcome = $response;
                   2019:             } else {
                   2020:                 $outcome = 'ok';
                   2021:                 my @matches = split(/\n/,$response);
                   2022:                 foreach my $match (@matches) {
                   2023:                     my ($key,$value) = split(/=/,$match);
                   2024:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2025:                 }
1.899     raeburn  2026:             }
                   2027:         }
                   2028:     }
1.909     raeburn  2029:     return ($outcome,%results);
1.899     raeburn  2030: }
                   2031: 
                   2032: sub usersearch {
                   2033:     my ($srch) = @_;
                   2034:     my $dom = $srch->{'srchdomain'};
                   2035:     my %results;
                   2036:     my %libserv = &all_library();
                   2037:     my $query = 'usersearch';
                   2038:     foreach my $tryserver (keys(%libserv)) {
                   2039:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2040:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2041:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2042:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.116  raeburn  2043:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+)\'?$/);
                   2044:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2045:                              (($major == 2) && ($minor < 11)) ||
                   2046:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2047:                 }
                   2048:             }
1.899     raeburn  2049:             my $host=&hostname($tryserver);
                   2050:             my $queryid=
1.911     raeburn  2051:                 &reply("querysend:".&escape($query).':'.
                   2052:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2053:                        &escape($srch->{'srchtype'}).':'.
                   2054:                        &escape($srch->{'srchterm'}),$tryserver);
                   2055:             if ($queryid !~/^\Q$host\E\_/) {
                   2056:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2057:                 next;
1.899     raeburn  2058:             }
                   2059:             my $reply = &get_query_reply($queryid);
                   2060:             my $maxtries = 1;
                   2061:             my $tries = 1;
                   2062:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2063:                 $reply = &get_query_reply($queryid);
                   2064:                 $tries ++;
                   2065:             }
                   2066:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2067:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2068:             } else {
1.911     raeburn  2069:                 my @matches;
                   2070:                 if ($reply =~ /\n/) {
                   2071:                     @matches = split(/\n/,$reply);
                   2072:                 } else {
                   2073:                     @matches = split(/\&/,$reply);
                   2074:                 }
1.899     raeburn  2075:                 foreach my $match (@matches) {
                   2076:                     my ($uname,$udom,%userhash);
1.911     raeburn  2077:                     foreach my $entry (split(/:/,$match)) {
                   2078:                         my ($key,$value) =
                   2079:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2080:                         $userhash{$key} = $value;
                   2081:                         if ($key eq 'username') {
                   2082:                             $uname = $value;
                   2083:                         } elsif ($key eq 'domain') {
                   2084:                             $udom = $value;
1.911     raeburn  2085:                         }
1.899     raeburn  2086:                     }
                   2087:                     $results{$uname.':'.$udom} = \%userhash;
                   2088:                 }
                   2089:             }
                   2090:         }
                   2091:     }
                   2092:     return %results;
                   2093: }
                   2094: 
1.912     raeburn  2095: sub get_instuser {
                   2096:     my ($udom,$uname,$id) = @_;
                   2097:     my $homeserver = &domain($udom,'primary');
                   2098:     my ($outcome,%results);
                   2099:     if ($homeserver ne '') {
                   2100:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2101:                            &escape($id).':'.&escape($udom),$homeserver);
                   2102:         my $host=&hostname($homeserver);
                   2103:         if ($queryid !~/^\Q$host\E\_/) {
                   2104:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2105:             return;
                   2106:         }
                   2107:         my $response = &get_query_reply($queryid);
                   2108:         my $maxtries = 5;
                   2109:         my $tries = 1;
                   2110:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2111:             $response = &get_query_reply($queryid);
                   2112:             $tries ++;
                   2113:         }
                   2114:         if (!&error($response) && $response ne 'refused') {
                   2115:             if ($response eq 'unavailable') {
                   2116:                 $outcome = $response;
                   2117:             } else {
                   2118:                 $outcome = 'ok';
                   2119:                 my @matches = split(/\n/,$response);
                   2120:                 foreach my $match (@matches) {
                   2121:                     my ($key,$value) = split(/=/,$match);
                   2122:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2123:                 }
                   2124:             }
                   2125:         }
                   2126:     }
                   2127:     my %userinfo;
                   2128:     if (ref($results{$uname}) eq 'HASH') {
                   2129:         %userinfo = %{$results{$uname}};
                   2130:     } 
                   2131:     return ($outcome,%userinfo);
                   2132: }
                   2133: 
1.1172.2.69  raeburn  2134: sub get_multiple_instusers {
                   2135:     my ($udom,$users,$caller) = @_;
                   2136:     my ($outcome,$results);
                   2137:     if (ref($users) eq 'HASH') {
                   2138:         my $count = keys(%{$users});
                   2139:         my $requested = &freeze_escape($users);
                   2140:         my $homeserver = &domain($udom,'primary');
                   2141:         if ($homeserver ne '') {
                   2142:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2143:             my $host=&hostname($homeserver);
                   2144:             if ($queryid !~/^\Q$host\E\_/) {
                   2145:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2146:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2147:                 return ($outcome,$results);
                   2148:             }
                   2149:             my $response = &get_query_reply($queryid);
                   2150:             my $maxtries = 5;
                   2151:             if ($count > 100) {
                   2152:                 $maxtries = 1+int($count/20);
                   2153:             }
                   2154:             my $tries = 1;
                   2155:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2156:                 $response = &get_query_reply($queryid);
                   2157:                 $tries ++;
                   2158:             }
                   2159:             if ($response eq '') {
                   2160:                 $results = {};
                   2161:                 foreach my $key (keys(%{$users})) {
                   2162:                     my ($uname,$id);
                   2163:                     if ($caller eq 'id') {
                   2164:                         $id = $key;
                   2165:                     } else {
                   2166:                         $uname = $key;
                   2167:                     }
                   2168:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2169:                     $outcome = $resp;
                   2170:                     if ($resp eq 'ok') {
                   2171:                         %{$results} = (%{$results}, %info);
                   2172:                     } else {
                   2173:                         last;
                   2174:                     }
                   2175:                 }
                   2176:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2177:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2178:                     $outcome = $response;
                   2179:                 } else {
                   2180:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2181:                     if ($outcome eq 'ok') {
                   2182:                         $results = &thaw_unescape($userdata);
                   2183:                     }
                   2184:                 }
                   2185:             }
                   2186:         }
                   2187:     }
                   2188:     return ($outcome,$results);
                   2189: }
                   2190: 
1.912     raeburn  2191: sub inst_rulecheck {
1.923     raeburn  2192:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2193:     my %returnhash;
                   2194:     if ($udom ne '') {
                   2195:         if (ref($rules) eq 'ARRAY') {
                   2196:             @{$rules} = map {&escape($_);} (@{$rules});
                   2197:             my $rulestr = join(':',@{$rules});
                   2198:             my $homeserver=&domain($udom,'primary');
                   2199:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2200:                 my $response;
                   2201:                 if ($item eq 'username') {                
                   2202:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2203:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2204:                                               $homeserver));
1.923     raeburn  2205:                 } elsif ($item eq 'id') {
                   2206:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2207:                                               ':'.&escape($id).':'.$rulestr,
                   2208:                                               $homeserver));
1.945     raeburn  2209:                 } elsif ($item eq 'selfcreate') {
                   2210:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2211:                                                &escape($udom).':'.&escape($uname).
                   2212:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2213:                 }
1.912     raeburn  2214:                 if ($response ne 'refused') {
                   2215:                     my @pairs=split(/\&/,$response);
                   2216:                     foreach my $item (@pairs) {
                   2217:                         my ($key,$value)=split(/=/,$item,2);
                   2218:                         $key = &unescape($key);
                   2219:                         next if ($key =~ /^error: 2 /);
                   2220:                         $returnhash{$key}=&thaw_unescape($value);
                   2221:                     }
                   2222:                 }
                   2223:             }
                   2224:         }
                   2225:     }
                   2226:     return %returnhash;
                   2227: }
                   2228: 
                   2229: sub inst_userrules {
1.923     raeburn  2230:     my ($udom,$check) = @_;
1.912     raeburn  2231:     my (%ruleshash,@ruleorder);
                   2232:     if ($udom ne '') {
                   2233:         my $homeserver=&domain($udom,'primary');
                   2234:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2235:             my $response;
                   2236:             if ($check eq 'id') {
                   2237:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2238:                                  $homeserver);
1.943     raeburn  2239:             } elsif ($check eq 'email') {
                   2240:                 $response=&reply('instemailrules:'.&escape($udom),
                   2241:                                  $homeserver);
1.923     raeburn  2242:             } else {
                   2243:                 $response=&reply('instuserrules:'.&escape($udom),
                   2244:                                  $homeserver);
                   2245:             }
1.912     raeburn  2246:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2247:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2248:                 ($response ne 'no_such_host')) {
                   2249:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2250:                 my @pairs=split(/\&/,$hashitems);
                   2251:                 foreach my $item (@pairs) {
                   2252:                     my ($key,$value)=split(/=/,$item,2);
                   2253:                     $key = &unescape($key);
                   2254:                     next if ($key =~ /^error: 2 /);
                   2255:                     $ruleshash{$key}=&thaw_unescape($value);
                   2256:                 }
                   2257:                 my @esc_order = split(/\&/,$orderitems);
                   2258:                 foreach my $item (@esc_order) {
                   2259:                     push(@ruleorder,&unescape($item));
                   2260:                 }
                   2261:             }
                   2262:         }
                   2263:     }
                   2264:     return (\%ruleshash,\@ruleorder);
                   2265: }
                   2266: 
1.976     raeburn  2267: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2268: 
                   2269: sub get_domain_defaults {
1.1172.2.35  raeburn  2270:     my ($domain,$ignore_cache) = @_;
                   2271:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2272:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2273:     unless ($ignore_cache) {
                   2274:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2275:         if (defined($cached)) {
                   2276:             if (ref($result) eq 'HASH') {
                   2277:                 return %{$result};
                   2278:             }
1.943     raeburn  2279:         }
                   2280:     }
                   2281:     my %domdefaults;
                   2282:     my %domconfig =
1.989     raeburn  2283:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2284:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2285:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2286:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2287:                                   'coursecategories','autoenroll',
                   2288:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2289:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2290:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2291:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2292:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2293:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2294:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2295:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2296:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2297:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2298:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2299:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2300:     } else {
                   2301:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2302:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2303:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2304:     }
1.976     raeburn  2305:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2306:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2307:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2308:         } else {
                   2309:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2310:         }
1.1172.2.6  raeburn  2311:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2312:         foreach my $item (@usertools) {
                   2313:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2314:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2315:             }
                   2316:         }
1.1172.2.29  raeburn  2317:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2318:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2319:         }
1.976     raeburn  2320:     }
1.985     raeburn  2321:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2322:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2323:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2324:         }
                   2325:     }
1.1172.2.9  raeburn  2326:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2327:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2328:     }
1.989     raeburn  2329:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2330:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2331:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2332:         }
                   2333:     }
1.1047    raeburn  2334:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2335:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2336:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2337:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2338:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2339:         }
1.1172.2.41  raeburn  2340:         foreach my $type (@coursetypes) {
                   2341:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2342:                 unless ($type eq 'community') {
                   2343:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2344:                 }
                   2345:             }
                   2346:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2347:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2348:             }
1.1172.2.60  raeburn  2349:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2350:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2351:                     $domdefaults{$type.'postsubtimeout'} =
                   2352:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2353:                 }
                   2354:             }
1.1172.2.30  raeburn  2355:         }
1.1172.2.67  raeburn  2356:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2357:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2358:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2359:                 if (@clonecodes) {
                   2360:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2361:                 }
                   2362:             }
                   2363:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2364:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2365:         }
1.1172.2.103  raeburn  2366:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2367:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2368:         }
1.1047    raeburn  2369:     }
1.1073    raeburn  2370:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2371:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2372:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2373:         }
                   2374:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2375:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2376:         }
1.1172.2.62  raeburn  2377:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2378:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2379:         }
1.1073    raeburn  2380:     }
1.1172.2.41  raeburn  2381:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2382:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2383:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2384:                             'approval','limit');
                   2385:             foreach my $type (@coursetypes) {
                   2386:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2387:                     my @mgrdc = ();
                   2388:                     foreach my $item (@settings) {
                   2389:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2390:                             push(@mgrdc,$item);
                   2391:                         }
                   2392:                     }
                   2393:                     if (@mgrdc) {
                   2394:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2395:                     }
                   2396:                 }
                   2397:             }
                   2398:         }
                   2399:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2400:             foreach my $type (@coursetypes) {
                   2401:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2402:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2403:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2404:                     }
                   2405:                 }
                   2406:             }
                   2407:         }
                   2408:     }
1.1172.2.46  raeburn  2409:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2410:         $domdefaults{'catauth'} = 'std';
                   2411:         $domdefaults{'catunauth'} = 'std';
                   2412:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2413:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2414:         }
                   2415:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2416:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2417:         }
                   2418:     }
1.1172.2.76  raeburn  2419:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2420:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2421:     }
1.1172.2.89  raeburn  2422:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2423:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2424:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2425:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2426:         }
                   2427:     }
1.1172.2.23  raeburn  2428:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2429:     return %domdefaults;
                   2430: }
                   2431: 
1.1172.2.106  raeburn  2432: sub get_dom_cats {
                   2433:     my ($dom) = @_;
                   2434:     return unless (&domain($dom));
                   2435:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2436:     unless (defined($cached)) {
                   2437:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2438:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2439:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2440:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2441:             } else {
                   2442:                 $cats = {};
                   2443:             }
                   2444:         } else {
                   2445:             $cats = {};
                   2446:         }
                   2447:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2448:     }
                   2449:     return $cats;
                   2450: }
                   2451: 
                   2452: sub get_dom_instcats {
                   2453:     my ($dom) = @_;
                   2454:     return unless (&domain($dom));
                   2455:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2456:     unless (defined($cached)) {
                   2457:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2458:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2459:         if ($totcodes > 0) {
                   2460:             my $caller = 'global';
                   2461:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2462:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2463:                 $instcats = {
                   2464:                                 codes => \%codes,
                   2465:                                 codetitles => \@codetitles,
                   2466:                                 cat_titles => \%cat_titles,
                   2467:                                 cat_order => \%cat_order,
                   2468:                             };
                   2469:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2470:             }
                   2471:         }
                   2472:     }
                   2473:     return $instcats;
                   2474: }
                   2475: 
                   2476: sub retrieve_instcodes {
                   2477:     my ($coursecodes,$dom) = @_;
                   2478:     my $totcodes;
                   2479:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2480:     foreach my $course (keys(%courses)) {
                   2481:         if (ref($courses{$course}) eq 'HASH') {
                   2482:             if ($courses{$course}{'inst_code'} ne '') {
                   2483:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2484:                 $totcodes ++;
                   2485:             }
                   2486:         }
                   2487:     }
                   2488:     return $totcodes;
                   2489: }
                   2490: 
1.1172.2.113  raeburn  2491: # --------------------------------------------- Get domain config for passwords
                   2492: 
                   2493: sub get_passwdconf {
                   2494:     my ($dom) = @_;
                   2495:     my (%passwdconf,$gotconf,$lookup);
                   2496:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2497:     if (defined($cached)) {
                   2498:         if (ref($result) eq 'HASH') {
                   2499:             %passwdconf = %{$result};
                   2500:             $gotconf = 1;
                   2501:         }
                   2502:     }
                   2503:     unless ($gotconf) {
                   2504:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2505:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2506:             %passwdconf = %{$domconfig{'passwords'}};
                   2507:         }
                   2508:         my $cachetime = 24*60*60;
                   2509:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2510:     }
                   2511:     return %passwdconf;
                   2512: }
                   2513: 
1.344     www      2514: # --------------------------------------------------- Assign a key to a student
                   2515: 
                   2516: sub assign_access_key {
1.364     www      2517: #
                   2518: # a valid key looks like uname:udom#comments
                   2519: # comments are being appended
                   2520: #
1.498     www      2521:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2522:     $kdom=
1.620     albertel 2523:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2524:     $knum=
1.620     albertel 2525:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2526:     $cdom=
1.620     albertel 2527:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2528:     $cnum=
1.620     albertel 2529:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2530:     $udom=$env{'user.name'} unless (defined($udom));
                   2531:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2532:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2533:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2534:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2535:                                                   # assigned to this person
                   2536:                                                   # - this should not happen,
1.345     www      2537:                                                   # unless something went wrong
                   2538:                                                   # the first time around
                   2539: # ready to assign
1.364     www      2540:         $logentry=$1.'; '.$logentry;
1.496     www      2541:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2542:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2543: # key now belongs to user
1.346     www      2544: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2545:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2546:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2547:                 return 'ok';
                   2548:             } else {
                   2549:                 return 
                   2550:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2551: 	    }
                   2552:         } else {
                   2553:             return 'error: Could not assign key, try again later.';
                   2554:         }
1.364     www      2555:     } elsif (!$existing{$ckey}) {
1.345     www      2556: # the key does not exist
                   2557: 	return 'error: The key does not exist';
                   2558:     } else {
                   2559: # the key is somebody else's
                   2560: 	return 'error: The key is already in use';
                   2561:     }
1.344     www      2562: }
                   2563: 
1.364     www      2564: # ------------------------------------------ put an additional comment on a key
                   2565: 
                   2566: sub comment_access_key {
                   2567: #
                   2568: # a valid key looks like uname:udom#comments
                   2569: # comments are being appended
                   2570: #
                   2571:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2572:     $cdom=
1.620     albertel 2573:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2574:     $cnum=
1.620     albertel 2575:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2576:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2577:     if ($existing{$ckey}) {
                   2578:         $existing{$ckey}.='; '.$logentry;
                   2579: # ready to assign
1.367     www      2580:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2581:                                                  $cdom,$cnum) eq 'ok') {
                   2582: 	    return 'ok';
                   2583:         } else {
                   2584: 	    return 'error: Count not store comment.';
                   2585:         }
                   2586:     } else {
                   2587: # the key does not exist
                   2588: 	return 'error: The key does not exist';
                   2589:     }
                   2590: }
                   2591: 
1.344     www      2592: # ------------------------------------------------------ Generate a set of keys
                   2593: 
                   2594: sub generate_access_keys {
1.364     www      2595:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2596:     $cdom=
1.620     albertel 2597:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2598:     $cnum=
1.620     albertel 2599:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2600:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2601:     unless (($cdom) && ($cnum)) { return 0; }
                   2602:     if ($number>10000) { return 0; }
                   2603:     sleep(2); # make sure don't get same seed twice
                   2604:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2605:     my $total=0;
                   2606:     for (my $i=1;$i<=$number;$i++) {
                   2607:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2608:                   sprintf("%lx",int(100000*rand)).'-'.
                   2609:                   sprintf("%lx",int(100000*rand));
                   2610:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2611:        $newkey=~s/0/h/g; # and also 0 and O
                   2612:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2613:        if ($existing{$newkey}) {
                   2614:            $i--;
                   2615:        } else {
1.364     www      2616: 	  if (&put('accesskeys',
                   2617:               { $newkey => '# generated '.localtime().
1.620     albertel 2618:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2619:                            '; '.$logentry },
                   2620: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2621:               $total++;
                   2622: 	  }
                   2623:        }
                   2624:     }
1.620     albertel 2625:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2626:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2627:     return $total;
                   2628: }
                   2629: 
                   2630: # ------------------------------------------------------- Validate an accesskey
                   2631: 
                   2632: sub validate_access_key {
                   2633:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2634:     $cdom=
1.620     albertel 2635:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2636:     $cnum=
1.620     albertel 2637:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2638:     $udom=$env{'user.domain'} unless (defined($udom));
                   2639:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2640:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2641:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2642: }
                   2643: 
                   2644: # ------------------------------------- Find the section of student in a course
1.652     albertel 2645: sub devalidate_getsection_cache {
                   2646:     my ($udom,$unam,$courseid)=@_;
                   2647:     my $hashid="$udom:$unam:$courseid";
                   2648:     &devalidate_cache_new('getsection',$hashid);
                   2649: }
1.298     matthew  2650: 
1.815     albertel 2651: sub courseid_to_courseurl {
                   2652:     my ($courseid) = @_;
                   2653:     #already url style courseid
                   2654:     return $courseid if ($courseid =~ m{^/});
                   2655: 
                   2656:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2657: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2658: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2659: 	return "/$cdom/$cnum";
                   2660:     }
                   2661: 
                   2662:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2663:     if (exists($courseinfo{'num'})) {
                   2664: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2665:     }
                   2666: 
                   2667:     return undef;
                   2668: }
                   2669: 
1.298     matthew  2670: sub getsection {
                   2671:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2672:     my $cachetime=1800;
1.551     albertel 2673: 
                   2674:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2675:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2676:     if (defined($cached)) { return $result; }
                   2677: 
1.298     matthew  2678:     my %Pending; 
                   2679:     my %Expired;
                   2680:     #
                   2681:     # Each role can either have not started yet (pending), be active, 
                   2682:     #    or have expired.
                   2683:     #
                   2684:     # If there is an active role, we are done.
                   2685:     #
                   2686:     # If there is more than one role which has not started yet, 
                   2687:     #     choose the one which will start sooner
                   2688:     # If there is one role which has not started yet, return it.
                   2689:     #
                   2690:     # If there is more than one expired role, choose the one which ended last.
                   2691:     # If there is a role which has expired, return it.
                   2692:     #
1.815     albertel 2693:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2694:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2695:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2696:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2697:         my $section=$1;
                   2698:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2699:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2700:         my $now=time;
1.548     albertel 2701:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2702:             $Expired{$end}=$section;
                   2703:             next;
                   2704:         }
1.548     albertel 2705:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2706:             $Pending{$start}=$section;
                   2707:             next;
                   2708:         }
1.599     albertel 2709:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2710:     }
                   2711:     #
                   2712:     # Presumedly there will be few matching roles from the above
                   2713:     # loop and the sorting time will be negligible.
                   2714:     if (scalar(keys(%Pending))) {
                   2715:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2716:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2717:     } 
                   2718:     if (scalar(keys(%Expired))) {
                   2719:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2720:         my $time = pop(@sorted);
1.599     albertel 2721:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2722:     }
1.599     albertel 2723:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2724: }
1.70      www      2725: 
1.599     albertel 2726: sub save_cache {
                   2727:     &purge_remembered();
1.722     albertel 2728:     #&Apache::loncommon::validate_page();
1.620     albertel 2729:     undef(%env);
1.780     albertel 2730:     undef($env_loaded);
1.599     albertel 2731: }
1.452     albertel 2732: 
1.599     albertel 2733: my $to_remember=-1;
                   2734: my %remembered;
                   2735: my %accessed;
                   2736: my $kicks=0;
                   2737: my $hits=0;
1.849     albertel 2738: sub make_key {
                   2739:     my ($name,$id) = @_;
1.872     albertel 2740:     if (length($id) > 65 
                   2741: 	&& length(&escape($id)) > 200) {
                   2742: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2743:     }
1.849     albertel 2744:     return &escape($name.':'.$id);
                   2745: }
                   2746: 
1.599     albertel 2747: sub devalidate_cache_new {
                   2748:     my ($name,$id,$debug) = @_;
                   2749:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2750:     my $remembered_id=$name.':'.$id;
1.849     albertel 2751:     $id=&make_key($name,$id);
1.599     albertel 2752:     $memcache->delete($id);
1.1172.2.81  raeburn  2753:     delete($remembered{$remembered_id});
                   2754:     delete($accessed{$remembered_id});
1.599     albertel 2755: }
                   2756: 
                   2757: sub is_cached_new {
                   2758:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2759:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2760:                                      # keys in %remembered hash, which persists for
                   2761:                                      # duration of request (no restriction on key length).
                   2762:     if (exists($remembered{$remembered_id})) {
                   2763: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2764: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2765: 	$hits++;
1.1172.2.81  raeburn  2766: 	return ($remembered{$remembered_id},1);
1.599     albertel 2767:     }
1.1172.2.81  raeburn  2768:     $id=&make_key($name,$id);
1.599     albertel 2769:     my $value = $memcache->get($id);
                   2770:     if (!(defined($value))) {
                   2771: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2772: 	return (undef,undef);
1.416     albertel 2773:     }
1.599     albertel 2774:     if ($value eq '__undef__') {
                   2775: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2776: 	$value=undef;
                   2777:     }
1.1172.2.81  raeburn  2778:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2779:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2780:     return ($value,1);
                   2781: }
                   2782: 
                   2783: sub do_cache_new {
                   2784:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2785:     my $remembered_id=$name.':'.$id;
1.849     albertel 2786:     $id=&make_key($name,$id);
1.599     albertel 2787:     my $setvalue=$value;
                   2788:     if (!defined($setvalue)) {
                   2789: 	$setvalue='__undef__';
                   2790:     }
1.623     albertel 2791:     if (!defined($time) ) {
                   2792: 	$time=600;
                   2793:     }
1.599     albertel 2794:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2795:     my $result = $memcache->set($id,$setvalue,$time);
                   2796:     if (! $result) {
1.872     albertel 2797: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2798: 	$memcache->disconnect_all();
1.872     albertel 2799:     }
1.600     albertel 2800:     # need to make a copy of $value
1.1172.2.81  raeburn  2801:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2802:     return $value;
                   2803: }
                   2804: 
                   2805: sub make_room {
1.1172.2.81  raeburn  2806:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2807: 
1.1172.2.81  raeburn  2808:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2809:                                     : $value;
1.599     albertel 2810:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2811:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2812:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2813:     my $to_kick;
                   2814:     my $max_time=0;
                   2815:     foreach my $other (keys(%accessed)) {
                   2816: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2817: 	    $to_kick=$other;
                   2818: 	    $max_time=&tv_interval($accessed{$other});
                   2819: 	}
                   2820:     }
                   2821:     delete($remembered{$to_kick});
                   2822:     delete($accessed{$to_kick});
                   2823:     $kicks++;
                   2824:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2825:     return;
                   2826: }
                   2827: 
1.599     albertel 2828: sub purge_remembered {
1.604     albertel 2829:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2830:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2831:     undef(%remembered);
                   2832:     undef(%accessed);
1.428     albertel 2833: }
1.70      www      2834: # ------------------------------------- Read an entry from a user's environment
                   2835: 
                   2836: sub userenvironment {
                   2837:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2838:     my $items;
                   2839:     foreach my $item (@what) {
                   2840:         $items.=&escape($item).'&';
                   2841:     }
                   2842:     $items=~s/\&$//;
1.70      www      2843:     my %returnhash=();
1.1009    raeburn  2844:     my $uhome = &homeserver($unam,$udom);
                   2845:     unless ($uhome eq 'no_host') {
                   2846:         my @answer=split(/\&/, 
                   2847:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2848:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2849:             return %returnhash;
                   2850:         }
1.1009    raeburn  2851:         my $i;
                   2852:         for ($i=0;$i<=$#what;$i++) {
                   2853: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2854:         }
1.70      www      2855:     }
                   2856:     return %returnhash;
1.1       albertel 2857: }
                   2858: 
1.617     albertel 2859: # ---------------------------------------------------------- Get a studentphoto
                   2860: sub studentphoto {
                   2861:     my ($udom,$unam,$ext) = @_;
                   2862:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2863:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2864:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2865:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2866:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2867:             } else {
                   2868:                 my ($result,$perm_reqd)=
1.707     albertel 2869: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2870:                 if ($result eq 'ok') {
                   2871:                     if (!($perm_reqd eq 'yes')) {
                   2872:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2873:                     }
                   2874:                 }
                   2875:             }
                   2876:         }
                   2877:     } else {
                   2878:         my ($result,$perm_reqd) = 
1.707     albertel 2879: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2880:         if ($result eq 'ok') {
                   2881:             if (!($perm_reqd eq 'yes')) {
                   2882:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2883:             }
                   2884:         }
                   2885:     }
                   2886:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2887: }
                   2888: 
                   2889: sub retrievestudentphoto {
                   2890:     my ($udom,$unam,$ext,$type) = @_;
                   2891:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2892:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2893:     if ($ret eq 'ok') {
                   2894:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2895:         if ($type eq 'thumbnail') {
                   2896:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2897:         }
                   2898:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2899:         return $tokenurl;
                   2900:     } else {
                   2901:         if ($type eq 'thumbnail') {
                   2902:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2903:         } else { 
                   2904:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2905:         }
1.617     albertel 2906:     }
                   2907: }
                   2908: 
1.263     www      2909: # -------------------------------------------------------------------- New chat
                   2910: 
                   2911: sub chatsend {
1.724     raeburn  2912:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2913:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2914:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2915:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2916:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2917: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2918: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2919: }
                   2920: 
                   2921: # ------------------------------------------ Find current version of a resource
                   2922: 
                   2923: sub getversion {
                   2924:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2925:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2926:     return &currentversion(&filelocation('',$fname));
                   2927: }
                   2928: 
                   2929: sub currentversion {
                   2930:     my $fname=shift;
                   2931:     my $author=$fname;
                   2932:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2933:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2934:     my $home=&homeserver($uname,$udom);
1.292     www      2935:     if ($home eq 'no_host') { 
                   2936:         return -1; 
                   2937:     }
1.1112    www      2938:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2939:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2940: 	return -1;
                   2941:     }
1.1112    www      2942:     return $answer;
1.263     www      2943: }
                   2944: 
1.1111    www      2945: #
                   2946: # Return special version number of resource if set by override, empty otherwise
                   2947: #
                   2948: sub usedversion {
                   2949:     my $fname=shift;
                   2950:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2951:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2952:     if ($urlversion) { return $urlversion; }
                   2953:     return '';
                   2954: }
                   2955: 
1.1       albertel 2956: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2957: 
1.1       albertel 2958: sub subscribe {
                   2959:     my $fname=shift;
1.761     raeburn  2960:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2961:     $fname=~s/[\n\r]//g;
1.1       albertel 2962:     my $author=$fname;
                   2963:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2964:     my ($udom,$uname)=split(/\//,$author);
                   2965:     my $home=homeserver($uname,$udom);
1.335     albertel 2966:     if ($home eq 'no_host') {
                   2967:         return 'not_found';
1.1       albertel 2968:     }
                   2969:     my $answer=reply("sub:$fname",$home);
1.64      www      2970:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2971: 	$answer.=' by '.$home;
                   2972:     }
1.1       albertel 2973:     return $answer;
                   2974: }
                   2975:     
1.8       www      2976: # -------------------------------------------------------------- Replicate file
                   2977: 
                   2978: sub repcopy {
                   2979:     my $filename=shift;
1.23      www      2980:     $filename=~s/\/+/\//g;
1.1142    raeburn  2981:     my $londocroot = $perlvar{'lonDocRoot'};
                   2982:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2983:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2984:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2985: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2986: 	return &repcopy_userfile($filename);
                   2987:     }
1.532     albertel 2988:     $filename=~s/[\n\r]//g;
1.8       www      2989:     my $transname="$filename.in.transfer";
1.828     www      2990: # FIXME: this should flock
1.607     raeburn  2991:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2992:     my $remoteurl=subscribe($filename);
1.64      www      2993:     if ($remoteurl =~ /^con_lost by/) {
                   2994: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2995:            return 'unavailable';
1.8       www      2996:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2997: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2998: 	   return 'not_found';
1.64      www      2999:     } elsif ($remoteurl =~ /^rejected by/) {
                   3000: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3001:            return 'forbidden';
1.20      www      3002:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3003:            return 'ok';
1.8       www      3004:     } else {
1.290     www      3005:         my $author=$filename;
                   3006:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3007:         my ($udom,$uname)=split(/\//,$author);
                   3008:         my $home=homeserver($uname,$udom);
                   3009:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3010:            my @parts=split(/\//,$filename);
                   3011:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3012:            if ($path ne "$londocroot/res") {
1.8       www      3013:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3014: 	       return 'bad_request';
1.8       www      3015:            }
                   3016:            my $count;
                   3017:            for ($count=5;$count<$#parts;$count++) {
                   3018:                $path.="/$parts[$count]";
                   3019:                if ((-e $path)!=1) {
                   3020: 		   mkdir($path,0777);
                   3021:                }
                   3022:            }
                   3023:            my $ua=new LWP::UserAgent;
                   3024:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3025:            my $response=$ua->request($request,$transname);
                   3026:            if ($response->is_error()) {
                   3027: 	       unlink($transname);
                   3028:                my $message=$response->status_line;
1.672     albertel 3029:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3030:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3031:                return 'unavailable';
1.8       www      3032:            } else {
1.16      www      3033: 	       if ($remoteurl!~/\.meta$/) {
                   3034:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3035:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3036:                   if ($mresponse->is_error()) {
                   3037: 		      unlink($filename.'.meta');
                   3038:                       &logthis(
1.672     albertel 3039:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3040:                   }
                   3041: 	       }
1.8       www      3042:                rename($transname,$filename);
1.607     raeburn  3043:                return 'ok';
1.8       www      3044:            }
1.290     www      3045:        }
1.8       www      3046:     }
1.330     www      3047: }
                   3048: 
                   3049: # ------------------------------------------------ Get server side include body
                   3050: sub ssi_body {
1.381     albertel 3051:     my ($filelink,%form)=@_;
1.606     matthew  3052:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3053:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3054:     }
1.953     www      3055:     my $output='';
                   3056:     my $response;
1.980     raeburn  3057:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3058:        ($output,$response)=&externalssi($filelink);
1.953     www      3059:     } else {
1.1004    droeschl 3060:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3061:        $filelink .= 'inhibitmenu=yes';
1.953     www      3062:        ($output,$response)=&ssi($filelink,%form);
                   3063:     }
1.778     albertel 3064:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3065:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3066:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3067:     if (wantarray) {
                   3068:         return ($output, $response);
                   3069:     } else {
                   3070:         return $output;
                   3071:     }
1.8       www      3072: }
                   3073: 
1.15      www      3074: # --------------------------------------------------------- Server Side Include
                   3075: 
1.782     albertel 3076: sub absolute_url {
                   3077:     my ($host_name) = @_;
                   3078:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3079:     if ($host_name eq '') {
                   3080: 	$host_name = $ENV{'SERVER_NAME'};
                   3081:     }
                   3082:     return $protocol.$host_name;
                   3083: }
                   3084: 
1.942     foxr     3085: #
                   3086: #   Server side include.
                   3087: # Parameters:
                   3088: #  fn     Possibly encrypted resource name/id.
                   3089: #  form   Hash that describes how the rendering should be done
                   3090: #         and other things.
1.944     foxr     3091: # Returns:
1.950     raeburn  3092: #   Scalar context: The content of the response.
                   3093: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3094: #     
1.15      www      3095: sub ssi {
                   3096: 
1.944     foxr     3097:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3098:     my ($request,$response);
1.711     albertel 3099: 
                   3100:     $form{'no_update_last_known'}=1;
1.895     albertel 3101:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3102:     if (%form) {
1.782     albertel 3103:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3104:       $request->content(join('&',map {
                   3105:             my $name = escape($_);
                   3106:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3107:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3108:             : &escape($form{$_}) );
                   3109:         } keys(%form)));
1.23      www      3110:     } else {
1.782     albertel 3111:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3112:     }
                   3113: 
1.15      www      3114:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3115: 
1.1172.2.101  raeburn  3116:     if (($env{'request.course.id'}) &&
                   3117:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3118:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3119:         ($form{'grade_symb'} ne '') &&
                   3120:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3121:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3122:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3123:             my $ua=new LWP::UserAgent;
                   3124:             $ua->local_address('127.0.0.1');
                   3125:             $response = $ua->request($request);
                   3126:         } else {
                   3127:             {
                   3128:                 require LWP::Protocol::http;
                   3129:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3130:                 my $ua=new LWP::UserAgent;
                   3131:                 $response = $ua->request($request);
                   3132:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3133:             }
                   3134:         }
                   3135:     } else {
                   3136:         my $ua=new LWP::UserAgent;
                   3137:         $response = $ua->request($request);
                   3138:     }
1.944     foxr     3139:     if (wantarray) {
1.1172.2.3  raeburn  3140: 	return ($response->content, $response);
1.944     foxr     3141:     } else {
1.1172.2.3  raeburn  3142: 	return $response->content;
1.942     foxr     3143:     }
1.324     www      3144: }
                   3145: 
                   3146: sub externalssi {
                   3147:     my ($url)=@_;
                   3148:     my $ua=new LWP::UserAgent;
                   3149:     my $request=new HTTP::Request('GET',$url);
                   3150:     my $response=$ua->request($request);
1.954     raeburn  3151:     if (wantarray) {
                   3152:         return ($response->content, $response);
                   3153:     } else {
                   3154:         return $response->content;
                   3155:     }
1.15      www      3156: }
1.254     www      3157: 
1.1172.2.98  raeburn  3158: # If the local copy of a replicated resource is outdated, trigger a
                   3159: # connection from the homeserver to flush the delayed queue. If no update
                   3160: # happens, remove local copies of outdated resource (and corresponding
                   3161: # metadata file).
                   3162: 
                   3163: sub remove_stale_resfile {
                   3164:     my ($url) = @_;
                   3165:     my $removed;
                   3166:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3167:         my $audom = $1;
                   3168:         my $auname = $2;
                   3169:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3170:             my $homeserver = &homeserver($auname,$audom);
                   3171:             unless (($homeserver eq 'no_host') ||
                   3172:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3173:                 my $fname = &filelocation('',$url);
                   3174:                 if (-e $fname) {
                   3175:                     my $ua=new LWP::UserAgent;
                   3176:                     $ua->timeout(5);
                   3177:                     my $protocol = $protocol{$homeserver};
                   3178:                     $protocol = 'http' if ($protocol ne 'https');
                   3179:                     my $hostname = &hostname($homeserver);
                   3180:                     if ($hostname) {
                   3181:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   3182:                         my $request=new HTTP::Request('HEAD',$uri);
                   3183:                         my $response=$ua->request($request);
                   3184:                         if ($response->is_success()) {
                   3185:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3186:                             my $locmodtime = (stat($fname))[9];
                   3187:                             if ($locmodtime < $remmodtime) {
                   3188:                                 my $stale;
                   3189:                                 my $answer = &reply('pong',$homeserver);
                   3190:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3191:                                     sleep(0.2);
                   3192:                                     $locmodtime = (stat($fname))[9];
                   3193:                                     if ($locmodtime < $remmodtime) {
                   3194:                                         my $posstransfer = $fname.'.in.transfer';
                   3195:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3196:                                             $removed = 1;
                   3197:                                         } else {
                   3198:                                             $stale = 1;
                   3199:                                         }
                   3200:                                     } else {
                   3201:                                         $removed = 1;
                   3202:                                     }
                   3203:                                 } else {
                   3204:                                     $stale = 1;
                   3205:                                 }
                   3206:                                 if ($stale) {
                   3207:                                     unlink($fname);
                   3208:                                     if ($uri!~/\.meta$/) {
                   3209:                                         unlink($fname.'.meta');
                   3210:                                     }
                   3211:                                     &reply("unsub:$fname",$homeserver);
                   3212:                                     $removed = 1;
                   3213:                                 }
                   3214:                             }
                   3215:                         }
                   3216:                     }
                   3217:                 }
                   3218:             }
                   3219:         }
                   3220:     }
                   3221:     return $removed;
                   3222: }
                   3223: 
1.492     albertel 3224: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3225: 
                   3226: sub allowuploaded {
                   3227:     my ($srcurl,$url)=@_;
                   3228:     $url=&clutter(&declutter($url));
                   3229:     my $dir=$url;
                   3230:     $dir=~s/\/[^\/]+$//;
                   3231:     my %httpref=();
                   3232:     my $httpurl=&hreflocation('',$url);
                   3233:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3234:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3235: }
1.477     raeburn  3236: 
1.1172.2.13  raeburn  3237: #
                   3238: # Determine if the current user should be able to edit a particular resource,
                   3239: # when viewing in course context.
                   3240: # (a) When viewing resource used to determine if "Edit" item is included in
                   3241: #     Functions.
                   3242: # (b) When displaying folder contents in course editor, used to determine if
                   3243: #     "Edit" link will be displayed alongside resource.
                   3244: #
                   3245: #  input: six args -- filename (decluttered), course number, course domain,
                   3246: #                   url, symb (if registered) and group (if this is a group
                   3247: #                   item -- e.g., bulletin board, group page etc.).
                   3248: #  output: array of five scalars --
                   3249: #          $cfile -- url for file editing if editable on current server
                   3250: #          $home -- homeserver of resource (i.e., for author if published,
                   3251: #                                           or course if uploaded.).
                   3252: #          $switchserver --  1 if server switch will be needed.
                   3253: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3254: #          $forceview -- 1 if icon/link should be to go to view mode
                   3255: #
                   3256: 
                   3257: sub can_edit_resource {
                   3258:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3259:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3260: #
                   3261: # For aboutme pages user can only edit his/her own.
                   3262: #
                   3263:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3264:         my ($sdom,$sname) = ($1,$2);
                   3265:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3266:             $home = $env{'user.home'};
                   3267:             $cfile = $resurl;
                   3268:             if ($env{'form.forceedit'}) {
                   3269:                 $forceview = 1;
                   3270:             } else {
                   3271:                 $forceedit = 1;
                   3272:             }
                   3273:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3274:         } else {
                   3275:             return;
                   3276:         }
                   3277:     }
                   3278: 
                   3279:     if ($env{'request.course.id'}) {
                   3280:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3281:         if ($group ne '') {
                   3282: # if this is a group homepage or group bulletin board, check group privs
                   3283:             my $allowed = 0;
                   3284:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3285:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3286:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3287:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3288:                     $allowed = 1;
                   3289:                 }
                   3290:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3291:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3292:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3293:                     $allowed = 1;
                   3294:                 }
                   3295:             }
                   3296:             if ($allowed) {
                   3297:                 $home=&homeserver($cnum,$cdom);
                   3298:                 if ($env{'form.forceedit'}) {
                   3299:                     $forceview = 1;
                   3300:                 } else {
                   3301:                     $forceedit = 1;
                   3302:                 }
                   3303:                 $cfile = $resurl;
                   3304:             } else {
                   3305:                 return;
                   3306:             }
                   3307:         } else {
1.1172.2.15  raeburn  3308:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3309:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3310:                     return;
                   3311:                 }
                   3312:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3313: #
                   3314: # No edit allowed where CC has switched to student role.
                   3315: #
                   3316:                 return;
                   3317:             }
                   3318:         }
                   3319:     }
                   3320: 
                   3321:     if ($file ne '') {
                   3322:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3323:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3324:                 $uploaded = 1;
                   3325:                 $incourse = 1;
                   3326:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3327:                     $cfile = &hreflocation('',$file);
                   3328:                     if ($env{'form.forceedit'}) {
                   3329:                         $forceview = 1;
                   3330:                     } else {
                   3331:                         $forceedit = 1;
                   3332:                     }
                   3333:                 }
                   3334:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3335:                 $incourse = 1;
                   3336:                 if ($env{'form.forceedit'}) {
                   3337:                     $forceview = 1;
                   3338:                 } else {
                   3339:                     $forceedit = 1;
                   3340:                 }
                   3341:                 $cfile = $resurl;
                   3342:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3343:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3344:                     $incourse = 1;
                   3345:                     if ($env{'form.forceedit'}) {
                   3346:                         $forceview = 1;
                   3347:                     } else {
                   3348:                         $forceedit = 1;
                   3349:                     }
                   3350:                     $cfile = $resurl;
                   3351:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3352:                     $incourse = 1;
                   3353:                     $cfile = $resurl.'/smpedit';
                   3354:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3355:                     $incourse = 1;
                   3356:                     if ($env{'form.forceedit'}) {
                   3357:                         $forceview = 1;
                   3358:                     } else {
                   3359:                         $forceedit = 1;
                   3360:                     }
                   3361:                     $cfile = $resurl;
1.1172.2.15  raeburn  3362:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3363:                     $incourse = 1;
                   3364:                     if ($env{'form.forceedit'}) {
                   3365:                         $forceview = 1;
                   3366:                     } else {
                   3367:                         $forceedit = 1;
                   3368:                     }
                   3369:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3370:                 }
                   3371:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3372:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3373:                 if (&is_on_map($template)) {
                   3374:                     $incourse = 1;
                   3375:                     $forceview = 1;
                   3376:                     $cfile = $template;
                   3377:                 }
                   3378:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118! raeburn  3379:                 $incourse = 1;
        !          3380:                 if ($env{'form.forceedit'}) {
        !          3381:                     $forceview = 1;
        !          3382:                 } else {
        !          3383:                     $forceedit = 1;
        !          3384:                 }
        !          3385:                 $cfile = $resurl;
1.1172.2.13  raeburn  3386:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3387:                 $incourse = 1;
                   3388:                 $forceview = 1;
                   3389:                 if ($symb) {
                   3390:                     my ($map,$id,$res)=&decode_symb($symb);
                   3391:                     $env{'request.symb'} = $symb;
                   3392:                     $cfile = &clutter($res);
                   3393:                 } else {
                   3394:                     $cfile = $env{'form.suppurl'};
                   3395:                     $cfile =~ s{^http://}{};
                   3396:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3397:                 }
1.1172.2.31  raeburn  3398:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3399:                 if ($env{'form.forceedit'}) {
                   3400:                     $forceview = 1;
                   3401:                 } else {
                   3402:                     $forceedit = 1;
                   3403:                 }
                   3404:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3405:             }
                   3406:         }
                   3407:         if ($uploaded || $incourse) {
                   3408:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3409:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3410:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3411:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3412:             # Check that the user has permission to edit this resource
                   3413:             my $setpriv = 1;
                   3414:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3415:             if (defined($cfudom)) {
                   3416:                 $home=&homeserver($cfuname,$cfudom);
                   3417:                 $cfile=$file;
                   3418:             }
                   3419:         }
                   3420:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3421:             (($home ne '') && ($home ne 'no_host'))) {
                   3422:             my @ids=&current_machine_ids();
                   3423:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3424:                 $switchserver=1;
                   3425:             }
                   3426:         }
                   3427:     }
                   3428:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3429: }
                   3430: 
                   3431: sub is_course_upload {
                   3432:     my ($file,$cnum,$cdom) = @_;
                   3433:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3434:     $uploadpath =~ s{^\/}{};
                   3435:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3436:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3437:         return 1;
                   3438:     }
                   3439:     return;
                   3440: }
                   3441: 
                   3442: sub in_course {
                   3443:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3444:     if ($hideprivileged) {
                   3445:         my $skipuser;
1.1172.2.23  raeburn  3446:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3447:         my @possdoms = ($cdom);
                   3448:         if ($coursehash{'checkforpriv'}) {
                   3449:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3450:         }
                   3451:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3452:             $skipuser = 1;
                   3453:             if ($coursehash{'nothideprivileged'}) {
                   3454:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3455:                     my $user;
                   3456:                     if ($item =~ /:/) {
                   3457:                         $user = $item;
                   3458:                     } else {
                   3459:                         $user = join(':',split(/[\@]/,$item));
                   3460:                     }
                   3461:                     if ($user eq $uname.':'.$udom) {
                   3462:                         undef($skipuser);
                   3463:                         last;
                   3464:                     }
                   3465:                 }
                   3466:             }
                   3467:             if ($skipuser) {
                   3468:                 return 0;
                   3469:             }
                   3470:         }
                   3471:     }
                   3472:     $type ||= 'any';
                   3473:     if (!defined($cdom) || !defined($cnum)) {
                   3474:         my $cid  = $env{'request.course.id'};
                   3475:         $cdom = $env{'course.'.$cid.'.domain'};
                   3476:         $cnum = $env{'course.'.$cid.'.num'};
                   3477:     }
                   3478:     my $typesref;
                   3479:     if (($type eq 'any') || ($type eq 'all')) {
                   3480:         $typesref = ['active','previous','future'];
                   3481:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3482:         $typesref = [$type];
                   3483:     }
                   3484:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3485:                               $typesref,undef,[$cdom]);
                   3486:     my ($tmp) = keys(%roles);
                   3487:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3488:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3489:     if (@course_roles > 0) {
                   3490:         return 1;
                   3491:     }
                   3492:     return 0;
                   3493: }
                   3494: 
1.478     albertel 3495: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3496: # input: action, courseID, current domain, intended
1.637     raeburn  3497: #        path to file, source of file, instruction to parse file for objects,
                   3498: #        ref to hash for embedded objects,
                   3499: #        ref to hash for codebase of java objects.
1.1095    raeburn  3500: #        reference to scalar to accommodate mime type determined
                   3501: #          from File::MMagic if $parser = parse.
1.637     raeburn  3502: #
1.485     raeburn  3503: # output: url to file (if action was uploaddoc), 
                   3504: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3505: #
1.478     albertel 3506: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3507: # course.
1.477     raeburn  3508: #
1.478     albertel 3509: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3510: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3511: #          course's home server.
1.477     raeburn  3512: #
1.478     albertel 3513: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3514: #          be copied from $source (current location) to 
                   3515: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3516: #         and will then be copied to
                   3517: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3518: #         course's home server.
1.485     raeburn  3519: #
1.481     raeburn  3520: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3521: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3522: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3523: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3524: #         in course's home server.
1.637     raeburn  3525: #
1.477     raeburn  3526: 
                   3527: sub process_coursefile {
1.1095    raeburn  3528:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3529:         $mimetype)=@_;
1.477     raeburn  3530:     my $fetchresult;
1.638     albertel 3531:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3532:     if ($action eq 'propagate') {
1.638     albertel 3533:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3534: 			     $home);
1.481     raeburn  3535:     } else {
1.477     raeburn  3536:         my $fpath = '';
                   3537:         my $fname = $file;
1.478     albertel 3538:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3539:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3540:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3541:         if ($action eq 'copy') {
                   3542:             if ($source eq '') {
                   3543:                 $fetchresult = 'no source file';
                   3544:                 return $fetchresult;
                   3545:             } else {
                   3546:                 my $destination = $filepath.'/'.$fname;
                   3547:                 rename($source,$destination);
                   3548:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3549:                                  $home);
1.481     raeburn  3550:             }
                   3551:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3552:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3553:             print $fh $env{'form.'.$source};
1.481     raeburn  3554:             close($fh);
1.637     raeburn  3555:             if ($parser eq 'parse') {
1.1024    raeburn  3556:                 my $mm = new File::MMagic;
1.1095    raeburn  3557:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3558:                 if ($type eq 'text/html') {
1.1024    raeburn  3559:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3560:                     unless ($parse_result eq 'ok') {
                   3561:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3562:                     }
1.637     raeburn  3563:                 }
1.1095    raeburn  3564:                 if (ref($mimetype)) {
                   3565:                     $$mimetype = $type;
                   3566:                 } 
1.637     raeburn  3567:             }
1.477     raeburn  3568:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3569:                                  $home);
1.481     raeburn  3570:             if ($fetchresult eq 'ok') {
                   3571:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3572:             } else {
                   3573:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3574:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3575:                 return '/adm/notfound.html';
                   3576:             }
1.477     raeburn  3577:         }
                   3578:     }
1.485     raeburn  3579:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3580:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3581:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3582:     }
                   3583:     return $fetchresult;
                   3584: }
                   3585: 
1.637     raeburn  3586: sub build_filepath {
                   3587:     my ($fpath) = @_;
                   3588:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3589:     unless ($fpath eq '') {
                   3590:         my @parts=split('/',$fpath);
                   3591:         foreach my $part (@parts) {
                   3592:             $filepath.= '/'.$part;
                   3593:             if ((-e $filepath)!=1) {
                   3594:                 mkdir($filepath,0777);
                   3595:             }
                   3596:         }
                   3597:     }
                   3598:     return $filepath;
                   3599: }
                   3600: 
                   3601: sub store_edited_file {
1.638     albertel 3602:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3603:     my $file = $primary_url;
                   3604:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3605:     my $fpath = '';
                   3606:     my $fname = $file;
                   3607:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3608:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3609:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3610:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3611:     print $fh $content;
                   3612:     close($fh);
1.638     albertel 3613:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3614:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3615: 			  $home);
1.637     raeburn  3616:     if ($$fetchresult eq 'ok') {
                   3617:         return '/uploaded/'.$fpath.'/'.$fname;
                   3618:     } else {
1.638     albertel 3619:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3620: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3621:         return '/adm/notfound.html';
                   3622:     }
                   3623: }
                   3624: 
1.531     albertel 3625: sub clean_filename {
1.831     albertel 3626:     my ($fname,$args)=@_;
1.315     www      3627: # Replace Windows backslashes by forward slashes
1.257     www      3628:     $fname=~s/\\/\//g;
1.831     albertel 3629:     if (!$args->{'keep_path'}) {
                   3630:         # Get rid of everything but the actual filename
                   3631: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3632:     }
1.315     www      3633: # Replace spaces by underscores
                   3634:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3635: # Transliterate non-ascii text to ascii
                   3636:     my $lang = &Apache::lonlocal::current_language();
                   3637:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3638: # Replace all other weird characters by nothing
1.831     albertel 3639:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3640: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3641: # numbers
                   3642:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3643:     return $fname;
                   3644: }
1.1172.2.110  raeburn  3645: 
1.1051    raeburn  3646: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3647: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3648: # image with the same aspect ratio as the original, but with dimensions which do 
                   3649: # not exceed $resizewidth and $resizeheight.
                   3650:  
1.984     neumanie 3651: sub resizeImage {
1.1051    raeburn  3652:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3653:     my $ima = Image::Magick->new;
                   3654:     my $resized;
                   3655:     if (-e $img_path) {
                   3656:         $ima->Read($img_path);
                   3657:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3658:             my $width = $ima->Get('width');
                   3659:             my $height = $ima->Get('height');
                   3660:             if ($width > $resizewidth) {
                   3661: 	        my $factor = $width/$resizewidth;
                   3662:                 my $newheight = $height/$factor;
                   3663:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3664:                 $resized = 1;
                   3665:             }
                   3666:         }
                   3667:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3668:             my $width = $ima->Get('width');
                   3669:             my $height = $ima->Get('height');
                   3670:             if ($height > $resizeheight) {
                   3671:                 my $factor = $height/$resizeheight;
                   3672:                 my $newwidth = $width/$factor;
                   3673:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3674:                 $resized = 1;
                   3675:             }
                   3676:         }
                   3677:         if ($resized) {
                   3678:             $ima->Write($img_path);
                   3679:         }
                   3680:     }
                   3681:     return;
1.977     amueller 3682: }
                   3683: 
1.608     albertel 3684: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3685: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3686: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3687: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3688: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3689: #                   if 'coursedoc': upload to the current course
                   3690: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3691: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3692: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3693: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3694: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3695: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3696: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3697: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3698: #        $allfiles - reference to hash for embedded objects
                   3699: #        $codebase - reference to hash for codebase of java objects
                   3700: #        $desuname - username for permanent storage of uploaded file
                   3701: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3702: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3703: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3704: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3705: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3706: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3707: #                    from File::MMagic.
1.858     raeburn  3708: # 
1.686     albertel 3709: # output: url of file in userspace, or error: <message> 
                   3710: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3711: 
1.531     albertel 3712: sub userfileupload {
1.1090    raeburn  3713:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3714:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3715:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3716:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3717:     $fname=&clean_filename($fname);
1.1090    raeburn  3718:     # See if there is anything left
1.257     www      3719:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3720:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3721:     if ($fname =~ /^\./) {
                   3722:         my ($s,$usec) = &gettimeofday();
                   3723:         while (length($usec) < 6) {
                   3724:             $usec = '0'.$usec;
                   3725:         }
                   3726:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3727:     }
1.1090    raeburn  3728:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3729:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3730:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3731:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3732:         my $now = time;
1.1090    raeburn  3733:         my $filepath;
1.1095    raeburn  3734:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3735:              $filepath = 'tmp/helprequests/'.$now;
                   3736:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3737:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3738:                          '_'.$env{'user.domain'}.'/pending';
                   3739:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3740:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3741:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3742:                 $docudom = $destudom;
                   3743:             } else {
                   3744:                 $docudom = $env{'user.domain'};
                   3745:             }
1.1172.2.96  raeburn  3746:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3747:                 $docuname = $destuname;
                   3748:             } else {
                   3749:                 $docuname = $env{'user.name'};
                   3750:             }
                   3751:             if (exists($env{'form.group'})) {
                   3752:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3753:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3754:             }
                   3755:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3756:             if ($context eq 'canceloverwrite') {
                   3757:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3758:                 if (-e  $tempfile) {
                   3759:                     my @info = stat($tempfile);
                   3760:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3761:                         unlink($tempfile);
                   3762:                     }
                   3763:                 }
                   3764:                 return;
1.523     raeburn  3765:             }
                   3766:         }
1.1090    raeburn  3767:         # Create the directory if not present
1.741     raeburn  3768:         my @parts=split(/\//,$filepath);
                   3769:         my $fullpath = $perlvar{'lonDaemons'};
                   3770:         for (my $i=0;$i<@parts;$i++) {
                   3771:             $fullpath .= '/'.$parts[$i];
                   3772:             if ((-e $fullpath)!=1) {
                   3773:                 mkdir($fullpath,0777);
                   3774:             }
                   3775:         }
1.1172.2.96  raeburn  3776:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3777:         print $fh $env{'form.'.$formname};
                   3778:         close($fh);
1.1090    raeburn  3779:         if ($context eq 'existingfile') {
                   3780:             my @info = stat($fullpath.'/'.$fname);
                   3781:             return ($fullpath.'/'.$fname,$info[9]);
                   3782:         } else {
                   3783:             return $fullpath.'/'.$fname;
                   3784:         }
1.523     raeburn  3785:     }
1.995     raeburn  3786:     if ($subdir eq 'scantron') {
                   3787:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3788:     } else {
1.995     raeburn  3789:         $fname="$subdir/$fname";
                   3790:     }
1.1090    raeburn  3791:     if ($context eq 'coursedoc') {
1.638     albertel 3792: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3793: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3794:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3795:             return &finishuserfileupload($docuname,$docudom,
                   3796: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3797: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3798:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3799:         } else {
1.1172.2.21  raeburn  3800:             if ($env{'form.folder'}) {
                   3801:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3802:             }
1.638     albertel 3803:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3804: 				       $fname,$formname,$parser,
1.1095    raeburn  3805: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3806:         }
1.719     banghart 3807:     } elsif (defined($destuname)) {
                   3808:         my $docuname=$destuname;
                   3809:         my $docudom=$destudom;
1.860     raeburn  3810: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3811: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3812:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3813:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3814:     } else {
1.638     albertel 3815:         my $docuname=$env{'user.name'};
                   3816:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3817:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3818:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3819:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3820:         }
1.860     raeburn  3821: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3822: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3823:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3824:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3825:     }
1.271     www      3826: }
                   3827: 
                   3828: sub finishuserfileupload {
1.860     raeburn  3829:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3830:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3831:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3832:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3833:   
1.860     raeburn  3834:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3835:     $file=$fname;
                   3836:     if ($fname=~m|/|) {
                   3837:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3838: 	$path.=$fnamepath.'/';
                   3839:     }
1.259     www      3840:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3841:     my $count;
                   3842:     for ($count=4;$count<=$#parts;$count++) {
                   3843:         $filepath.="/$parts[$count]";
                   3844:         if ((-e $filepath)!=1) {
                   3845: 	    mkdir($filepath,0777);
                   3846:         }
                   3847:     }
1.984     neumanie 3848: 
1.258     www      3849: # Save the file
                   3850:     {
1.1172.2.96  raeburn  3851: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3852: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3853: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3854: 	    return '/adm/notfound.html';
                   3855: 	}
1.1090    raeburn  3856:         if ($context eq 'overwrite') {
1.1117    foxr     3857:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3858:             my $target = $filepath.'/'.$file;
                   3859:             if (-e $source) {
                   3860:                 my @info = stat($source);
                   3861:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3862:                     unless (&File::Copy::move($source,$target)) {
                   3863:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3864:                         return "Moving from $source failed";
                   3865:                     }
                   3866:                 } else {
                   3867:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3868:                 }
                   3869:             } else {
                   3870:                 return "Temporary file: $source missing";
                   3871:             }
                   3872:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3873: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3874: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3875: 	    return '/adm/notfound.html';
                   3876: 	}
1.570     albertel 3877: 	close(FH);
1.1051    raeburn  3878:         if ($resizewidth && $resizeheight) {
                   3879:             my $mm = new File::MMagic;
                   3880:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3881:             if ($mime_type =~ m{^image/}) {
                   3882: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3883:             }  
1.977     amueller 3884: 	}
1.258     www      3885:     }
1.1152    raeburn  3886:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3887:         if (ref($mimetype)) {
                   3888:             if ($$mimetype eq '') {
                   3889:                 my $mm = new File::MMagic;
                   3890:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3891:                 $$mimetype = $type;
                   3892:             }
                   3893:         }
                   3894:     }
1.1172.2.109  raeburn  3895:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3896:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3897:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3898:                                                        $allfiles,$codebase);
                   3899:             unless ($parse_result eq 'ok') {
                   3900:                 &logthis('Failed to parse '.$filepath.$file.
                   3901: 	   	         ' for embedded media: '.$parse_result); 
                   3902:             }
1.637     raeburn  3903:         }
1.1172.2.109  raeburn  3904:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3905:         my $format = $env{'form.scantron_format'};
                   3906:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3907:     }
1.860     raeburn  3908:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3909:         my $input = $filepath.'/'.$file;
                   3910:         my $output = $filepath.'/'.'tn-'.$file;
                   3911:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3912:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3913:         system({$args[0]} @args);
1.860     raeburn  3914:         if (-e $filepath.'/'.'tn-'.$file) {
                   3915:             $fetchthumb  = 1; 
                   3916:         }
                   3917:     }
1.858     raeburn  3918:  
1.259     www      3919: # Notify homeserver to grep it
                   3920: #
1.984     neumanie 3921:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3922:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3923:     if ($fetchresult eq 'ok') {
1.860     raeburn  3924:         if ($fetchthumb) {
                   3925:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3926:             if ($thumbresult ne 'ok') {
                   3927:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3928:                          $docuhome.': '.$thumbresult);
                   3929:             }
                   3930:         }
1.259     www      3931: #
1.258     www      3932: # Return the URL to it
1.494     albertel 3933:         return '/uploaded/'.$path.$file;
1.263     www      3934:     } else {
1.494     albertel 3935:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3936: 		 ': '.$fetchresult);
1.263     www      3937:         return '/adm/notfound.html';
1.858     raeburn  3938:     }
1.493     albertel 3939: }
                   3940: 
1.637     raeburn  3941: sub extract_embedded_items {
1.961     raeburn  3942:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3943:     my @state = ();
1.1164    raeburn  3944:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3945:     my %javafiles = (
                   3946:                       codebase => '',
                   3947:                       code => '',
                   3948:                       archive => ''
                   3949:                     );
                   3950:     my %mediafiles = (
                   3951:                       src => '',
                   3952:                       movie => '',
                   3953:                      );
1.648     raeburn  3954:     my $p;
                   3955:     if ($content) {
                   3956:         $p = HTML::LCParser->new($content);
                   3957:     } else {
1.961     raeburn  3958:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3959:     }
1.641     albertel 3960:     while (my $t=$p->get_token()) {
1.640     albertel 3961: 	if ($t->[0] eq 'S') {
                   3962: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3963: 	    push(@state, $tagname);
1.648     raeburn  3964:             if (lc($tagname) eq 'allow') {
                   3965:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3966:             }
1.640     albertel 3967: 	    if (lc($tagname) eq 'img') {
                   3968: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3969: 	    }
1.886     albertel 3970: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3971:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3972: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3973:                 }
1.886     albertel 3974: 	    }
1.645     raeburn  3975:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3976:                 my $src;
1.645     raeburn  3977:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3978:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3979:                 } else {
1.1164    raeburn  3980:                     if ($attr->{'src'} ne '') {
                   3981:                         $src = $attr->{'src'};
                   3982:                         &add_filetype($allfiles,$src,'src');
                   3983:                     }
                   3984:                 }
                   3985:                 my $text = $p->get_trimmed_text();
                   3986:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3987:                     my @swfargs = split(/,/,$1);
                   3988:                     foreach my $item (@swfargs) {
                   3989:                         $item =~ s/["']//g;
                   3990:                         $item =~ s/^\s+//;
                   3991:                         $item =~ s/\s+$//;
                   3992:                     }
                   3993:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3994:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3995:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3996:                         } else {
                   3997:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3998:                         }
                   3999:                     }
1.645     raeburn  4000:                 }
                   4001:             }
                   4002:             if (lc($tagname) eq 'link') {
                   4003:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4004:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4005:                 }
                   4006:             }
1.640     albertel 4007: 	    if (lc($tagname) eq 'object' ||
                   4008: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4009: 		foreach my $item (keys(%javafiles)) {
                   4010: 		    $javafiles{$item} = '';
                   4011: 		}
1.1164    raeburn  4012:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4013:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4014:                 }
1.640     albertel 4015: 	    }
                   4016: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4017: 		my $name = lc($attr->{'name'});
                   4018: 		foreach my $item (keys(%javafiles)) {
                   4019: 		    if ($name eq $item) {
                   4020: 			$javafiles{$item} = $attr->{'value'};
                   4021: 			last;
                   4022: 		    }
                   4023: 		}
1.1164    raeburn  4024:                 my $pathfrom;
1.640     albertel 4025: 		foreach my $item (keys(%mediafiles)) {
                   4026: 		    if ($name eq $item) {
1.1164    raeburn  4027:                         $pathfrom = $attr->{'value'};
                   4028:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4029: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4030: 			last;
                   4031: 		    }
                   4032: 		}
1.1164    raeburn  4033:                 if ($name eq 'flashvars') {
                   4034:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4035:                 }
                   4036:                 if ($pathfrom ne '') {
                   4037:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4038:                                          $pathfrom);
                   4039:                 }
1.640     albertel 4040: 	    }
                   4041: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4042: 		foreach my $item (keys(%javafiles)) {
                   4043: 		    if ($attr->{$item}) {
                   4044: 			$javafiles{$item} = $attr->{$item};
                   4045: 			last;
                   4046: 		    }
                   4047: 		}
                   4048: 		foreach my $item (keys(%mediafiles)) {
                   4049: 		    if ($attr->{$item}) {
                   4050: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4051: 			last;
                   4052: 		    }
                   4053: 		}
1.1164    raeburn  4054:                 if (lc($tagname) eq 'embed') {
                   4055:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4056:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4057:                                              $attr->{'src'});
                   4058:                     }
                   4059:                 }
1.640     albertel 4060: 	    }
1.1172.2.35  raeburn  4061:             if (lc($tagname) eq 'iframe') {
                   4062:                 my $src = $attr->{'src'} ;
                   4063:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4064:                     &add_filetype($allfiles,$src,'src');
                   4065:                 } elsif ($src =~ m{^/}) {
                   4066:                     if ($env{'request.course.id'}) {
                   4067:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4068:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4069:                         my $url = &hreflocation('',$fullpath);
                   4070:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4071:                             my $relpath = $1;
                   4072:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4073:                                 &add_filetype($allfiles,$1,'src');
                   4074:                             }
                   4075:                         }
                   4076:                     }
                   4077:                 }
                   4078:             }
1.1164    raeburn  4079:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4080:                 pop(@state);
1.1164    raeburn  4081:             }
1.640     albertel 4082: 	} elsif ($t->[0] eq 'E') {
                   4083: 	    my ($tagname) = ($t->[1]);
                   4084: 	    if ($javafiles{'codebase'} ne '') {
                   4085: 		$javafiles{'codebase'} .= '/';
                   4086: 	    }  
                   4087: 	    if (lc($tagname) eq 'applet' ||
                   4088: 		lc($tagname) eq 'object' ||
                   4089: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4090: 		) {
                   4091: 		foreach my $item (keys(%javafiles)) {
                   4092: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4093: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4094: 			&add_filetype($allfiles,$file,$item);
                   4095: 		    }
                   4096: 		}
                   4097: 	    } 
                   4098: 	    pop @state;
                   4099: 	}
                   4100:     }
1.1164    raeburn  4101:     foreach my $id (sort(keys(%flashvars))) {
                   4102:         if ($shockwave{$id} ne '') {
                   4103:             my @pairs = split(/\&/,$flashvars{$id});
                   4104:             foreach my $pair (@pairs) {
                   4105:                 my ($key,$value) = split(/\=/,$pair);
                   4106:                 if ($key eq 'thumb') {
                   4107:                     &add_filetype($allfiles,$value,$key);
                   4108:                 } elsif ($key eq 'content') {
                   4109:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4110:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4111:                     if ($ext ne '') {
                   4112:                         &add_filetype($allfiles,$path.$value,$ext);
                   4113:                     }
                   4114:                 }
                   4115:             }
                   4116:         }
                   4117:     }
1.637     raeburn  4118:     return 'ok';
                   4119: }
                   4120: 
1.639     albertel 4121: sub add_filetype {
                   4122:     my ($allfiles,$file,$type)=@_;
                   4123:     if (exists($allfiles->{$file})) {
                   4124: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4125: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4126: 	}
                   4127:     } else {
                   4128: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4129:     }
                   4130: }
                   4131: 
1.1164    raeburn  4132: sub embedded_dependency {
                   4133:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4134:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4135:         if (($identifier ne '') &&
                   4136:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4137:             ($pathfrom ne '')) {
                   4138:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4139:             foreach my $dep (@{$related->{$identifier}}) {
                   4140:                 &add_filetype($allfiles,$path.$dep,'object');
                   4141:             }
                   4142:         }
                   4143:     }
                   4144:     return;
                   4145: }
                   4146: 
1.1172.2.109  raeburn  4147: sub bubblesheet_converter {
                   4148:     my ($cdom,$fullpath,$config,$format) = @_;
                   4149:     if ((&domain($cdom) ne '') &&
                   4150:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4151:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4152:         my (%csvcols,%csvoptions);
                   4153:         if (ref($config->{'fields'}) eq 'HASH') {
                   4154:             %csvcols = %{$config->{'fields'}};
                   4155:         }
                   4156:         if (ref($config->{'options'}) eq 'HASH') {
                   4157:             %csvoptions = %{$config->{'options'}};
                   4158:         }
                   4159:         my %csvbynum = reverse(%csvcols);
                   4160:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4161:         if (keys(%scantronconf)) {
                   4162:             my %bynum = (
                   4163:                           $scantronconf{CODEstart} => 'CODEstart',
                   4164:                           $scantronconf{IDstart}   => 'IDstart',
                   4165:                           $scantronconf{PaperID}   => 'PaperID',
                   4166:                           $scantronconf{FirstName} => 'FirstName',
                   4167:                           $scantronconf{LastName}  => 'LastName',
                   4168:                           $scantronconf{Qstart}    => 'Qstart',
                   4169:                         );
                   4170:             my @ordered;
                   4171:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4172:                 push(@ordered,$bynum{$item});
                   4173:             }
                   4174:             my %mapstart = (
                   4175:                               CODEstart => 'CODE',
                   4176:                               IDstart   => 'ID',
                   4177:                               PaperID   => 'PaperID',
                   4178:                               FirstName => 'FirstName',
                   4179:                               LastName  => 'LastName',
                   4180:                               Qstart    => 'FirstQuestion',
                   4181:                            );
                   4182:             my %maplength = (
                   4183:                               CODEstart => 'CODElength',
                   4184:                               IDstart   => 'IDlength',
                   4185:                               PaperID   => 'PaperIDlength',
                   4186:                               FirstName => 'FirstNamelength',
                   4187:                               LastName  => 'LastNamelength',
                   4188:             );
                   4189:             if (open(my $fh,'<',$fullpath)) {
                   4190:                 my $output;
                   4191:                 my %lettdig = &letter_to_digits();
                   4192:                 my %diglett = reverse(%lettdig);
                   4193:                 my $numletts = scalar(keys(%lettdig));
                   4194:                 my $num = 0;
                   4195:                 while (my $line=<$fh>) {
                   4196:                     $num ++;
                   4197:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4198:                     $line =~ s{[\r\n]+$}{};
                   4199:                     my %found;
                   4200:                     my @values = split(/,/,$line);
                   4201:                     my ($qstart,$record);
                   4202:                     for (my $i=0; $i<@values; $i++) {
                   4203:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4204:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4205:                             if ($values[$i] eq '') {
                   4206:                                 $values[$i] = $scantronconf{'Qoff'};
                   4207:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4208:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4209:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4210:                                 }
                   4211:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4212:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4213:                                     $values[$i] = $diglett{$values[$i]};
                   4214:                                 }
                   4215:                             } else {
                   4216:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4217:                                     my $digit;
                   4218:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4219:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4220:                                         if ($values[$i] eq 'J') {
                   4221:                                             $digit += $numletts;
                   4222:                                         }
                   4223:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4224:                                         $digit = $values[$i]-1;
                   4225:                                         if ($values[$i] eq '0') {
                   4226:                                             $digit += $numletts;
                   4227:                                         }
                   4228:                                     }
                   4229:                                     my $qval='';
                   4230:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4231:                                         if ($j == $digit) {
                   4232:                                             $qval .= $scantronconf{'Qon'};
                   4233:                                         } else {
                   4234:                                             $qval .= $scantronconf{'Qoff'};
                   4235:                                         }
                   4236:                                     }
                   4237:                                     $values[$i] = $qval;
                   4238:                                 }
                   4239:                             }
                   4240:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4241:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4242:                             }
                   4243:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4244:                             if ($numblank > 0) {
                   4245:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4246:                             }
                   4247:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4248:                                 $qstart = $i;
                   4249:                                 $found{$csvbynum{$i}} = $values[$i];
                   4250:                             } else {
                   4251:                                 $found{'FirstQuestion'} .= $values[$i];
                   4252:                             }
                   4253:                         } elsif (exists($csvbynum{$i})) {
                   4254:                             if ($csvoptions{'rem'}) {
                   4255:                                 $values[$i] =~ s/^\s+//;
                   4256:                             }
                   4257:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4258:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4259:                                     $values[$i] = '0'.$values[$i];
                   4260:                                 }
                   4261:                             }
                   4262:                             $found{$csvbynum{$i}} = $values[$i];
                   4263:                         }
                   4264:                     }
                   4265:                     foreach my $item (@ordered) {
                   4266:                         my $currlength = 1+length($record);
                   4267:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4268:                         if ($numspaces > 0) {
                   4269:                             $record .= (' ' x $numspaces);
                   4270:                         }
                   4271:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4272:                             unless ($item eq 'Qstart') {
                   4273:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4274:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4275:                                 }
                   4276:                             }
                   4277:                             $record .= $found{$mapstart{$item}};
                   4278:                         }
                   4279:                     }
                   4280:                     $output .= "$record\n";
                   4281:                 }
                   4282:                 close($fh);
                   4283:                 if ($output) {
                   4284:                     if (open(my $fh,'>',$fullpath)) {
                   4285:                         print $fh $output;
                   4286:                         close($fh);
                   4287:                     }
                   4288:                 }
                   4289:             }
                   4290:         }
                   4291:         return;
                   4292:     }
                   4293: }
                   4294: 
                   4295: sub letter_to_digits {
                   4296:     my %lettdig = (
                   4297:                     A => 1,
                   4298:                     B => 2,
                   4299:                     C => 3,
                   4300:                     D => 4,
                   4301:                     E => 5,
                   4302:                     F => 6,
                   4303:                     G => 7,
                   4304:                     H => 8,
                   4305:                     I => 9,
                   4306:                     J => 0,
                   4307:                   );
                   4308:     return %lettdig;
                   4309: }
                   4310: 
                   4311: sub get_scantron_config {
                   4312:     my ($which,$cdom) = @_;
                   4313:     my @lines = &get_scantronformat_file($cdom);
                   4314:     my %config;
                   4315:     #FIXME probably should move to XML it has already gotten a bit much now
                   4316:     foreach my $line (@lines) {
                   4317:         my ($name,$descrip)=split(/:/,$line);
                   4318:         if ($name ne $which ) { next; }
                   4319:         chomp($line);
                   4320:         my @config=split(/:/,$line);
                   4321:         $config{'name'}=$config[0];
                   4322:         $config{'description'}=$config[1];
                   4323:         $config{'CODElocation'}=$config[2];
                   4324:         $config{'CODEstart'}=$config[3];
                   4325:         $config{'CODElength'}=$config[4];
                   4326:         $config{'IDstart'}=$config[5];
                   4327:         $config{'IDlength'}=$config[6];
                   4328:         $config{'Qstart'}=$config[7];
                   4329:         $config{'Qlength'}=$config[8];
                   4330:         $config{'Qoff'}=$config[9];
                   4331:         $config{'Qon'}=$config[10];
                   4332:         $config{'PaperID'}=$config[11];
                   4333:         $config{'PaperIDlength'}=$config[12];
                   4334:         $config{'FirstName'}=$config[13];
                   4335:         $config{'FirstNamelength'}=$config[14];
                   4336:         $config{'LastName'}=$config[15];
                   4337:         $config{'LastNamelength'}=$config[16];
                   4338:         $config{'BubblesPerRow'}=$config[17];
                   4339:         last;
                   4340:     }
                   4341:     return %config;
                   4342: }
                   4343: 
                   4344: sub get_scantronformat_file {
                   4345:     my ($cdom) = @_;
                   4346:     if ($cdom eq '') {
                   4347:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4348:     }
                   4349:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4350:     my $gottab = 0;
                   4351:     my @lines;
                   4352:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4353:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4354:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4355:             if ($formatfile ne '-1') {
                   4356:                 @lines = split("\n",$formatfile,-1);
                   4357:                 $gottab = 1;
                   4358:             }
                   4359:         }
                   4360:     }
                   4361:     if (!$gottab) {
                   4362:         my $confname = $cdom.'-domainconfig';
                   4363:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4364:         my $formatfile = &getfile($default);
                   4365:         if ($formatfile ne '-1') {
                   4366:             @lines = split("\n",$formatfile,-1);
                   4367:             $gottab = 1;
                   4368:         }
                   4369:     }
                   4370:     if (!$gottab) {
                   4371:         my @domains = &current_machine_domains();
                   4372:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4373:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4374:                 @lines = <$fh>;
                   4375:                 close($fh);
                   4376:             }
                   4377:         } else {
                   4378:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4379:                 @lines = <$fh>;
                   4380:                 close($fh);
                   4381:             }
                   4382:         }
                   4383:     }
                   4384:     return @lines;
                   4385: }
                   4386: 
1.493     albertel 4387: sub removeuploadedurl {
1.984     neumanie 4388:     my ($url)=@_;	
                   4389:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4390:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4391: }
                   4392: 
                   4393: sub removeuserfile {
                   4394:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4395:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4396:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4397:     if ($result eq 'ok') {	
1.798     raeburn  4398:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4399:             my $metafile = $fname.'.meta';
                   4400:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4401: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4402:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4403:             my $sqlresult = 
1.823     albertel 4404:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4405:                                         'portfolio_metadata',$group,
                   4406:                                         'delete');
1.798     raeburn  4407:         }
                   4408:     }
                   4409:     return $result;
1.257     www      4410: }
1.15      www      4411: 
1.530     albertel 4412: sub mkdiruserfile {
                   4413:     my ($docuname,$docudom,$dir)=@_;
                   4414:     my $home=&homeserver($docuname,$docudom);
                   4415:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4416: }
                   4417: 
1.531     albertel 4418: sub renameuserfile {
                   4419:     my ($docuname,$docudom,$old,$new)=@_;
                   4420:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4421:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4422:                         &escape("$old").':'.&escape("$new"),$home);
                   4423:     if ($result eq 'ok') {
                   4424:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4425:             my $oldmeta = $old.'.meta';
                   4426:             my $newmeta = $new.'.meta';
                   4427:             my $metaresult = 
                   4428:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4429: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4430:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4431:             my $sqlresult = 
1.823     albertel 4432:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4433:                                         'portfolio_metadata',$group,
                   4434:                                         'delete');
1.798     raeburn  4435:         }
                   4436:     }
                   4437:     return $result;
1.531     albertel 4438: }
                   4439: 
1.14      www      4440: # ------------------------------------------------------------------------- Log
                   4441: 
                   4442: sub log {
                   4443:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4444:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4445: }
                   4446: 
                   4447: # ------------------------------------------------------------------ Course Log
1.352     www      4448: #
                   4449: # This routine flushes several buffers of non-mission-critical nature
                   4450: #
1.157     www      4451: 
                   4452: sub flushcourselogs {
1.352     www      4453:     &logthis('Flushing log buffers');
                   4454: #
                   4455: # course logs
                   4456: # This is a log of all transactions in a course, which can be used
                   4457: # for data mining purposes
                   4458: #
                   4459: # It also collects the courseid database, which lists last transaction
                   4460: # times and course titles for all courseids
                   4461: #
                   4462:     my %courseidbuffer=();
1.921     raeburn  4463:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4464:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4465: 		          &escape($courselogs{$crsid}),
                   4466: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4467: 	    delete $courselogs{$crsid};
                   4468:         } else {
                   4469:             &logthis('Failed to flush log buffer for '.$crsid);
                   4470:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4471:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4472:                         " exceeded maximum size, deleting.</font>");
                   4473:                delete $courselogs{$crsid};
                   4474:             }
1.352     www      4475:         }
1.920     raeburn  4476:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4477:             'description' => $coursedescrbuf{$crsid},
                   4478:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4479:             'type'        => $coursetypebuf{$crsid},
                   4480:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4481:         };
1.191     harris41 4482:     }
1.352     www      4483: #
                   4484: # Write course id database (reverse lookup) to homeserver of courses 
                   4485: # Is used in pickcourse
                   4486: #
1.840     albertel 4487:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4488:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4489:                                     $courseidbuffer{$crs_home},
                   4490:                                     $crs_home,'timeonly');
1.352     www      4491:     }
                   4492: #
                   4493: # File accesses
                   4494: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4495: #
1.449     matthew  4496:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4497:         if ($entry =~ /___count$/) {
                   4498:             my ($dom,$name);
1.807     albertel 4499:             ($dom,$name,undef)=
1.811     albertel 4500: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4501:             if (! defined($dom) || $dom eq '' || 
                   4502:                 ! defined($name) || $name eq '') {
1.620     albertel 4503:                 my $cid = $env{'request.course.id'};
                   4504:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4505:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4506:             }
1.450     matthew  4507:             my $value = $accesshash{$entry};
                   4508:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4509:             my %temphash=($url => $value);
1.449     matthew  4510:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4511:             if ($result eq 'ok') {
                   4512:                 delete $accesshash{$entry};
                   4513:             }
                   4514:         } else {
1.811     albertel 4515:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4516:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4517:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4518:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4519:                 delete $accesshash{$entry};
                   4520:             }
1.185     www      4521:         }
1.191     harris41 4522:     }
1.352     www      4523: #
                   4524: # Roles
                   4525: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4526: #
1.800     albertel 4527:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4528:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4529: 	    split(/\:/,$entry);
                   4530:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4531:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4532:                 $rudom,$runame) eq 'ok') {
                   4533: 	    delete $userrolehash{$entry};
                   4534:         }
                   4535:     }
1.662     raeburn  4536: #
1.1172.2.90  raeburn  4537: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4538: #
                   4539:     my %domrolebuffer = ();
1.1000    raeburn  4540:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4541:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4542:         if ($domrolebuffer{$rudom}) {
                   4543:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4544:                       '='.&escape($domainrolehash{$entry});
                   4545:         } else {
                   4546:             $domrolebuffer{$rudom}.=&escape($entry).
                   4547:                       '='.&escape($domainrolehash{$entry});
                   4548:         }
                   4549:         delete $domainrolehash{$entry};
                   4550:     }
                   4551:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4552:         my %servers;
                   4553:         if (defined(&domain($dom,'primary'))) {
                   4554:             my $primary=&domain($dom,'primary');
                   4555:             my $hostname=&hostname($primary);
                   4556:             $servers{$primary} = $hostname;
                   4557:         } else {
                   4558:             %servers = &get_servers($dom,'library');
                   4559:         }
1.841     albertel 4560: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4561: 	    if (&reply('domroleput:'.$dom.':'.
                   4562: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4563: 	        last;
                   4564: 	    } else {
1.841     albertel 4565: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4566: 	    }
1.662     raeburn  4567:         }
                   4568:     }
1.186     www      4569:     $dumpcount++;
1.157     www      4570: }
                   4571: 
                   4572: sub courselog {
                   4573:     my $what=shift;
1.158     www      4574:     $what=time.':'.$what;
1.620     albertel 4575:     unless ($env{'request.course.id'}) { return ''; }
                   4576:     $coursedombuf{$env{'request.course.id'}}=
                   4577:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4578:     $coursenumbuf{$env{'request.course.id'}}=
                   4579:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4580:     $coursehombuf{$env{'request.course.id'}}=
                   4581:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4582:     $coursedescrbuf{$env{'request.course.id'}}=
                   4583:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4584:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4585:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4586:     $courseownerbuf{$env{'request.course.id'}}=
                   4587:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4588:     $coursetypebuf{$env{'request.course.id'}}=
                   4589:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4590:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4591: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4592:     } else {
1.620     albertel 4593: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4594:     }
1.620     albertel 4595:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4596: 	&flushcourselogs();
                   4597:     }
1.158     www      4598: }
                   4599: 
                   4600: sub courseacclog {
                   4601:     my $fnsymb=shift;
1.620     albertel 4602:     unless ($env{'request.course.id'}) { return ''; }
                   4603:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4604:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4605:         $what.=':POST';
1.583     matthew  4606:         # FIXME: Probably ought to escape things....
1.800     albertel 4607: 	foreach my $key (keys(%env)) {
                   4608:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4609:                 my $formitem = $1;
                   4610:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4611:                     $what.=':'.$formitem.'='.$env{$key};
                   4612:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4613:                     $what.=':'.$formitem.'='.$env{$key};
                   4614:                 }
1.158     www      4615:             }
1.191     harris41 4616:         }
1.583     matthew  4617:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4618:         # FIXME: We should not be depending on a form parameter that someone
                   4619:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4620:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4621:             $what.= ':POST';
                   4622:             # FIXME: Probably ought to escape things....
                   4623:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4624:                                  'crsdiscuss') {
1.620     albertel 4625:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4626:             }
                   4627:         }
1.158     www      4628:     }
                   4629:     &courselog($what);
1.149     www      4630: }
                   4631: 
1.185     www      4632: sub countacc {
                   4633:     my $url=&declutter(shift);
1.458     matthew  4634:     return if (! defined($url) || $url eq '');
1.620     albertel 4635:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4636: #
                   4637: # Mark that this url was used in this course
                   4638: #
1.620     albertel 4639:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4640: #
                   4641: # Increase the access count for this resource in this child process
                   4642: #
1.281     www      4643:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4644:     $accesshash{$key}++;
1.185     www      4645: }
1.349     www      4646: 
1.361     www      4647: sub linklog {
                   4648:     my ($from,$to)=@_;
                   4649:     $from=&declutter($from);
                   4650:     $to=&declutter($to);
                   4651:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4652:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4653: }
1.1160    www      4654: 
                   4655: sub statslog {
                   4656:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4657:     if ($users<2) { return; }
                   4658:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4659:             'course'       => $env{'request.course.id'},
                   4660:             'sections'     => '"all"',
                   4661:             'num_students' => $users,
                   4662:             'part'         => $part,
                   4663:             'symb'         => $symb,
                   4664:             'mean_tries'   => $av_attempts,
                   4665:             'deg_of_diff'  => $degdiff});
                   4666:     foreach my $key (keys(%dynstore)) {
                   4667:         $accesshash{$key}=$dynstore{$key};
                   4668:     }
                   4669: }
1.361     www      4670:   
1.349     www      4671: sub userrolelog {
                   4672:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4673:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4674:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4675:        $userrolehash
                   4676:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4677:                     =$tend.':'.$tstart;
1.662     raeburn  4678:     }
1.1169    droeschl 4679:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4680:        $userrolehash
                   4681:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4682:                     =$tend.':'.$tstart;
                   4683:     }
1.1172.2.90  raeburn  4684:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4685:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4686:        $domainrolehash
                   4687:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4688:                     = $tend.':'.$tstart;
                   4689:     }
1.351     www      4690: }
                   4691: 
1.957     raeburn  4692: sub courserolelog {
                   4693:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4694:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4695:         my $cdom = $1;
                   4696:         my $cnum = $2;
                   4697:         my $sec = $3;
                   4698:         my $namespace = 'rolelog';
                   4699:         my %storehash = (
                   4700:                            role    => $trole,
                   4701:                            start   => $tstart,
                   4702:                            end     => $tend,
                   4703:                            selfenroll => $selfenroll,
                   4704:                            context    => $context,
                   4705:                         );
                   4706:         if ($trole eq 'gr') {
                   4707:             $namespace = 'groupslog';
                   4708:             $storehash{'group'} = $sec;
                   4709:         } else {
                   4710:             $storehash{'section'} = $sec;
                   4711:         }
                   4712:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4713:                    $domain,$cnum,$cdom);
                   4714:         if (($trole ne 'st') || ($sec ne '')) {
                   4715:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4716:         }
                   4717:     }
                   4718:     return;
                   4719: }
                   4720: 
1.1172.2.9  raeburn  4721: sub domainrolelog {
                   4722:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4723:     if ($area =~ m{^/($match_domain)/$}) {
                   4724:         my $cdom = $1;
                   4725:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4726:         my $namespace = 'rolelog';
                   4727:         my %storehash = (
                   4728:                            role    => $trole,
                   4729:                            start   => $tstart,
                   4730:                            end     => $tend,
                   4731:                            context => $context,
                   4732:                         );
                   4733:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4734:                    $domain,$domconfiguser,$cdom);
                   4735:     }
                   4736:     return;
                   4737: 
                   4738: }
                   4739: 
                   4740: sub coauthorrolelog {
                   4741:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4742:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4743:         my $audom = $1;
                   4744:         my $auname = $2;
                   4745:         my $namespace = 'rolelog';
                   4746:         my %storehash = (
                   4747:                            role    => $trole,
                   4748:                            start   => $tstart,
                   4749:                            end     => $tend,
                   4750:                            context => $context,
                   4751:                         );
                   4752:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4753:                    $domain,$auname,$audom);
                   4754:     }
                   4755:     return;
                   4756: }
                   4757: 
1.351     www      4758: sub get_course_adv_roles {
1.948     raeburn  4759:     my ($cid,$codes) = @_;
1.620     albertel 4760:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4761:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4762:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4763:     my %nothide=();
1.800     albertel 4764:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4765:         if ($user !~ /:/) {
                   4766: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4767:         } else {
                   4768:             $nothide{$user}=1;
                   4769:         }
1.470     www      4770:     }
1.1172.2.23  raeburn  4771:     my @possdoms = ($coursehash{'domain'});
                   4772:     if ($coursehash{'checkforpriv'}) {
                   4773:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4774:     }
1.351     www      4775:     my %returnhash=();
                   4776:     my %dumphash=
                   4777:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4778:     my $now=time;
1.997     raeburn  4779:     my %privileged;
1.1000    raeburn  4780:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4781: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4782:         if (($tstart) && ($tstart<0)) { next; }
                   4783:         if (($tend) && ($tend<$now)) { next; }
                   4784:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4785:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4786: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4787:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4788:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4789: 	if ($role eq 'cr') { next; }
1.948     raeburn  4790:         if ($codes) {
                   4791:             if ($section) { $role .= ':'.$section; }
                   4792:             if ($returnhash{$role}) {
                   4793:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4794:             } else {
                   4795:                 $returnhash{$role}=$username.':'.$domain;
                   4796:             }
1.351     www      4797:         } else {
1.988     raeburn  4798:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4799:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4800:             if ($returnhash{$key}) {
                   4801: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4802:             } else {
                   4803:                 $returnhash{$key}=$username.':'.$domain;
                   4804:             }
1.351     www      4805:         }
1.948     raeburn  4806:     }
1.400     www      4807:     return %returnhash;
                   4808: }
                   4809: 
                   4810: sub get_my_roles {
1.937     raeburn  4811:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4812:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4813:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4814:     my (%dumphash,%nothide);
1.1086    raeburn  4815:     if ($context eq 'userroles') {
1.1166    raeburn  4816:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4817:     } else {
1.1172.2.23  raeburn  4818:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4819:         if ($hidepriv) {
                   4820:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4821:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4822:                 if ($user !~ /:/) {
                   4823:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4824:                 } else {
                   4825:                     $nothide{$user} = 1;
                   4826:                 }
                   4827:             }
                   4828:         }
1.858     raeburn  4829:     }
1.400     www      4830:     my %returnhash=();
                   4831:     my $now=time;
1.999     raeburn  4832:     my %privileged;
1.800     albertel 4833:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4834:         my ($role,$tend,$tstart);
                   4835:         if ($context eq 'userroles') {
1.1149    raeburn  4836:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4837: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4838:         } else {
                   4839:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4840:         }
1.400     www      4841:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4842:         my $status = 'active';
1.939     raeburn  4843:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4844:             $status = 'previous';
                   4845:         } 
                   4846:         if (($tstart) && ($now<$tstart)) {
                   4847:             $status = 'future';
                   4848:         }
                   4849:         if (ref($types) eq 'ARRAY') {
                   4850:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4851:                 next;
                   4852:             } 
                   4853:         } else {
                   4854:             if ($status ne 'active') {
                   4855:                 next;
                   4856:             }
                   4857:         }
1.867     raeburn  4858:         my ($rolecode,$username,$domain,$section,$area);
                   4859:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4860:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4861:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4862:         } else {
                   4863:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4864:         }
1.832     raeburn  4865:         if (ref($roledoms) eq 'ARRAY') {
                   4866:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4867:                 next;
                   4868:             }
                   4869:         }
                   4870:         if (ref($roles) eq 'ARRAY') {
                   4871:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4872:                 if ($role =~ /^cr\//) {
                   4873:                     if (!grep(/^cr$/,@{$roles})) {
                   4874:                         next;
                   4875:                     }
1.1104    raeburn  4876:                 } elsif ($role =~ /^gr\//) {
                   4877:                     if (!grep(/^gr$/,@{$roles})) {
                   4878:                         next;
                   4879:                     }
1.922     raeburn  4880:                 } else {
                   4881:                     next;
                   4882:                 }
1.832     raeburn  4883:             }
1.867     raeburn  4884:         }
1.937     raeburn  4885:         if ($hidepriv) {
1.1172.2.23  raeburn  4886:             my @privroles = ('dc','su');
1.999     raeburn  4887:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4888:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4889:             } else {
1.1172.2.23  raeburn  4890:                 my $possdoms = [$domain];
                   4891:                 if (ref($roledoms) eq 'ARRAY') {
                   4892:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4893:                 }
1.1172.2.23  raeburn  4894:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4895:                     if (!$nothide{$username.':'.$domain}) {
                   4896:                         next;
                   4897:                     }
                   4898:                 }
1.937     raeburn  4899:             }
                   4900:         }
1.933     raeburn  4901:         if ($withsec) {
                   4902:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4903:                 $tstart.':'.$tend;
                   4904:         } else {
                   4905:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4906:         }
1.832     raeburn  4907:     }
1.373     www      4908:     return %returnhash;
1.399     www      4909: }
                   4910: 
1.1172.2.89  raeburn  4911: sub get_all_adhocroles {
                   4912:     my ($dom) = @_;
                   4913:     my @roles_by_num = ();
                   4914:     my %domdefaults = &get_domain_defaults($dom);
                   4915:     my (%description,%access_in_dom,%access_info);
                   4916:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4917:         my $count = 0;
                   4918:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4919:         my %ordered;
                   4920:         foreach my $role (sort(keys(%domcurrent))) {
                   4921:             my ($order,$desc,$access_in_dom);
                   4922:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4923:                 $order = $domcurrent{$role}{'order'};
                   4924:                 $desc = $domcurrent{$role}{'desc'};
                   4925:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4926:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4927:             }
                   4928:             if ($order eq '') {
                   4929:                 $order = $count;
                   4930:             }
                   4931:             $ordered{$order} = $role;
                   4932:             if ($desc ne '') {
                   4933:                 $description{$role} = $desc;
                   4934:             } else {
                   4935:                 $description{$role}= $role;
                   4936:             }
                   4937:             $count++;
                   4938:         }
                   4939:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4940:             push(@roles_by_num,$ordered{$item});
                   4941:         }
                   4942:     }
                   4943:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4944: }
                   4945: 
                   4946: sub get_my_adhocroles {
                   4947:     my ($cid,$checkreg) = @_;
                   4948:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4949:     if ($env{'request.course.id'} eq $cid) {
                   4950:         $cdom = $env{'course.'.$cid.'.domain'};
                   4951:         $cnum = $env{'course.'.$cid.'.num'};
                   4952:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4953:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4954:         $cdom = $1;
                   4955:         $cnum = $2;
                   4956:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4957:                                      $cdom,$cnum);
                   4958:     }
                   4959:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4960:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4961:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4962:         if ($rosterhash{$user} ne '') {
                   4963:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4964:             return ([],{}) if ($type eq 'auto');
                   4965:         }
                   4966:     }
                   4967:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4968:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4969:             my $then=$env{'user.login.time'};
                   4970:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4971:             if (!$update) {
                   4972:                 $update = $then;
                   4973:             }
                   4974:             my @liveroles;
                   4975:             foreach my $role ('dh','da') {
                   4976:                 if ($env{"user.role.$role./$cdom/"}) {
                   4977:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4978:                     my $limit = $update;
                   4979:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4980:                         $limit = $then;
                   4981:                     }
                   4982:                     my $activerole = 1;
                   4983:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4984:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4985:                     if ($activerole) {
                   4986:                         push(@liveroles,$role);
                   4987:                     }
                   4988:                 }
                   4989:             }
                   4990:             if (@liveroles) {
1.1172.2.89  raeburn  4991:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4992:                     my ($accessref,$accessinfo,%access_in_dom);
                   4993:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4994:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4995:                         if (@{$roles_by_num}) {
                   4996:                             my %settings;
                   4997:                             if ($env{'request.course.id'} eq $cid) {
                   4998:                                 foreach my $envkey (keys(%env)) {
                   4999:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5000:                                         $settings{$1} = $env{$envkey};
                   5001:                                     }
                   5002:                                 }
                   5003:                             } else {
                   5004:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5005:                             }
                   5006:                             my %setincrs;
                   5007:                             if ($settings{'internal.adhocaccess'}) {
                   5008:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5009:                             }
                   5010:                             my @statuses;
                   5011:                             if ($env{'environment.inststatus'}) {
                   5012:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5013:                             }
                   5014:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5015:                             if (ref($accessref) eq 'HASH') {
                   5016:                                 %access_in_dom = %{$accessref};
                   5017:                             }
                   5018:                             foreach my $role (@{$roles_by_num}) {
                   5019:                                 my ($curraccess,@okstatus,@personnel);
                   5020:                                 if ($setincrs{$role}) {
                   5021:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5022:                                     if ($curraccess eq 'status') {
                   5023:                                         @okstatus = split(/\&/,$rest);
                   5024:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5025:                                         @personnel = split(/\&/,$rest);
                   5026:                                     }
                   5027:                                 } else {
                   5028:                                     $curraccess = $access_in_dom{$role};
                   5029:                                     if (ref($accessinfo) eq 'HASH') {
                   5030:                                         if ($curraccess eq 'status') {
                   5031:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5032:                                                 @okstatus = @{$accessinfo->{$role}};
                   5033:                                             }
                   5034:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5035:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5036:                                                 @personnel = @{$accessinfo->{$role}};
                   5037:                                             }
                   5038:                                         }
                   5039:                                     }
                   5040:                                 }
                   5041:                                 if ($curraccess eq 'none') {
                   5042:                                     next;
                   5043:                                 } elsif ($curraccess eq 'all') {
                   5044:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5045:                                 } elsif ($curraccess eq 'dh') {
                   5046:                                     if (grep(/^dh$/,@liveroles)) {
                   5047:                                         push(@possroles,$role);
                   5048:                                     } else {
                   5049:                                         next;
                   5050:                                     }
                   5051:                                 } elsif ($curraccess eq 'da') {
                   5052:                                     if (grep(/^da$/,@liveroles)) {
                   5053:                                         push(@possroles,$role);
                   5054:                                     } else {
                   5055:                                         next;
                   5056:                                     }
1.1172.2.89  raeburn  5057:                                 } elsif ($curraccess eq 'status') {
                   5058:                                     if (@okstatus) {
                   5059:                                         if (!@statuses) {
                   5060:                                             if (grep(/^default$/,@okstatus)) {
                   5061:                                                 push(@possroles,$role);
                   5062:                                             }
                   5063:                                         } else {
                   5064:                                             foreach my $status (@okstatus) {
                   5065:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5066:                                                     push(@possroles,$role);
                   5067:                                                     last;
                   5068:                                                 }
                   5069:                                             }
                   5070:                                         }
                   5071:                                     }
                   5072:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5073:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5074:                                         if ($curraccess eq 'exc') {
                   5075:                                             push(@possroles,$role);
                   5076:                                         }
                   5077:                                     } elsif ($curraccess eq 'inc') {
                   5078:                                         push(@possroles,$role);
                   5079:                                     }
                   5080:                                 }
                   5081:                             }
                   5082:                         }
                   5083:                     }
                   5084:                 }
                   5085:             }
                   5086:         }
                   5087:     }
                   5088:     unless (ref($description) eq 'HASH') {
                   5089:         if (ref($roles_by_num) eq 'ARRAY') {
                   5090:             my %desc;
                   5091:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5092:             $description = \%desc;
                   5093:         } else {
                   5094:             $description = {};
                   5095:         }
                   5096:     }
                   5097:     return (\@possroles,$description);
                   5098: }
                   5099: 
1.399     www      5100: # ----------------------------------------------------- Frontpage Announcements
                   5101: #
                   5102: #
                   5103: 
                   5104: sub postannounce {
                   5105:     my ($server,$text)=@_;
1.844     albertel 5106:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5107:     unless ($text=~/\w/) { $text=''; }
                   5108:     return &reply('setannounce:'.&escape($text),$server);
                   5109: }
                   5110: 
                   5111: sub getannounce {
1.448     albertel 5112: 
1.1172.2.96  raeburn  5113:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5114: 	my $announcement='';
1.800     albertel 5115: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5116: 	close($fh);
1.399     www      5117: 	if ($announcement=~/\w/) { 
                   5118: 	    return 
                   5119:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5120:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5121: 	} else {
                   5122: 	    return '';
                   5123: 	}
                   5124:     } else {
                   5125: 	return '';
                   5126:     }
1.351     www      5127: }
1.353     www      5128: 
                   5129: # ---------------------------------------------------------- Course ID routines
                   5130: # Deal with domain's nohist_courseid.db files
                   5131: #
                   5132: 
                   5133: sub courseidput {
1.921     raeburn  5134:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5135:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5136:     my $outcome;
                   5137:     if ($caller eq 'timeonly') {
                   5138:         my $cids = '';
                   5139:         foreach my $item (keys(%$storehash)) {
                   5140:             $cids.=&escape($item).'&';
                   5141:         }
                   5142:         $cids=~s/\&$//;
                   5143:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5144:                           $coursehome);       
                   5145:     } else {
                   5146:         my $items = '';
                   5147:         foreach my $item (keys(%$storehash)) {
                   5148:             $items.= &escape($item).'='.
                   5149:                      &freeze_escape($$storehash{$item}).'&';
                   5150:         }
                   5151:         $items=~s/\&$//;
                   5152:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5153:                           $coursehome);
1.918     raeburn  5154:     }
                   5155:     if ($outcome eq 'unknown_cmd') {
                   5156:         my $what;
                   5157:         foreach my $cid (keys(%$storehash)) {
                   5158:             $what .= &escape($cid).'=';
1.921     raeburn  5159:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5160:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5161:             }
                   5162:             $what =~ s/\:$/&/;
                   5163:         }
                   5164:         $what =~ s/\&$//;  
                   5165:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5166:     } else {
                   5167:         return $outcome;
                   5168:     }
1.353     www      5169: }
                   5170: 
                   5171: sub courseiddump {
1.921     raeburn  5172:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5173:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5174:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5175:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5176:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5177:     my $as_hash = 1;
                   5178:     my %returnhash;
                   5179:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5180:     my %libserv = &all_library();
                   5181:     foreach my $tryserver (keys(%libserv)) {
                   5182:         if ( (  $hostidflag == 1 
                   5183: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5184: 	     || (!defined($hostidflag)) ) {
                   5185: 
1.918     raeburn  5186: 	    if (($domfilter eq '') ||
                   5187: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5188:                 my $rep;
                   5189:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5190:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5191:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5192:                                 &escape($descfilter), &escape($instcodefilter),
                   5193:                                 &escape($ownerfilter), &escape($coursefilter),
                   5194:                                 &escape($typefilter), &escape($regexp_ok),
                   5195:                                 $as_hash, &escape($selfenrollonly),
                   5196:                                 &escape($catfilter), $showhidden, $caller,
                   5197:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5198:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5199:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5200:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5201:                 } else {
                   5202:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5203:                              $sincefilter.':'.&escape($descfilter).':'.
                   5204:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5205:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5206:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5207:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5208:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5209:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5210:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5211:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5212:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5213:                 }
                   5214: 
1.918     raeburn  5215:                 my @pairs=split(/\&/,$rep);
                   5216:                 foreach my $item (@pairs) {
                   5217:                     my ($key,$value)=split(/\=/,$item,2);
                   5218:                     $key = &unescape($key);
                   5219:                     next if ($key =~ /^error: 2 /);
                   5220:                     my $result = &thaw_unescape($value);
                   5221:                     if (ref($result) eq 'HASH') {
                   5222:                         $returnhash{$key}=$result;
                   5223:                     } else {
1.921     raeburn  5224:                         my @responses = split(/:/,$value);
                   5225:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5226:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5227:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5228:                         }
1.1008    raeburn  5229:                     }
1.353     www      5230:                 }
                   5231:             }
                   5232:         }
                   5233:     }
                   5234:     return %returnhash;
                   5235: }
                   5236: 
1.1055    raeburn  5237: sub courselastaccess {
                   5238:     my ($cdom,$cnum,$hostidref) = @_;
                   5239:     my %returnhash;
                   5240:     if ($cdom && $cnum) {
                   5241:         my $chome = &homeserver($cnum,$cdom);
                   5242:         if ($chome ne 'no_host') {
                   5243:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5244:             &extract_lastaccess(\%returnhash,$rep);
                   5245:         }
                   5246:     } else {
                   5247:         if (!$cdom) { $cdom=''; }
                   5248:         my %libserv = &all_library();
                   5249:         foreach my $tryserver (keys(%libserv)) {
                   5250:             if (ref($hostidref) eq 'ARRAY') {
                   5251:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5252:             } 
                   5253:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5254:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5255:                 &extract_lastaccess(\%returnhash,$rep);
                   5256:             }
                   5257:         }
                   5258:     }
                   5259:     return %returnhash;
                   5260: }
                   5261: 
                   5262: sub extract_lastaccess {
                   5263:     my ($returnhash,$rep) = @_;
                   5264:     if (ref($returnhash) eq 'HASH') {
                   5265:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5266:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5267:                  $rep eq '') {
                   5268:             my @pairs=split(/\&/,$rep);
                   5269:             foreach my $item (@pairs) {
                   5270:                 my ($key,$value)=split(/\=/,$item,2);
                   5271:                 $key = &unescape($key);
                   5272:                 next if ($key =~ /^error: 2 /);
                   5273:                 $returnhash->{$key} = &thaw_unescape($value);
                   5274:             }
                   5275:         }
                   5276:     }
                   5277:     return;
                   5278: }
                   5279: 
1.658     raeburn  5280: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5281: 
                   5282: sub dcmailput {
1.685     raeburn  5283:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5284:     my $status = &Apache::lonnet::critical(
1.740     www      5285:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5286:        &escape($message),$server);
1.662     raeburn  5287:     return $status;
                   5288: }
                   5289: 
1.658     raeburn  5290: sub dcmaildump {
                   5291:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5292:     my %returnhash=();
1.846     albertel 5293: 
                   5294:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5295:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5296:                                                          &escape($enddate).':';
                   5297: 	my @esc_senders=map { &escape($_)} @$senders;
                   5298: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5299: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5300:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5301:             if (($key) && ($value)) {
                   5302:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5303:             }
                   5304:         }
                   5305:     }
                   5306:     return %returnhash;
                   5307: }
1.662     raeburn  5308: # ---------------------------------------------------------- Domain roles
                   5309: 
                   5310: sub get_domain_roles {
                   5311:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5312:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5313:         $startdate = '.';
                   5314:     }
1.1018    raeburn  5315:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5316:         $enddate = '.';
                   5317:     }
1.922     raeburn  5318:     my $rolelist;
                   5319:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5320:         $rolelist = join('&',@{$roles});
1.922     raeburn  5321:     }
1.662     raeburn  5322:     my %personnel = ();
1.841     albertel 5323: 
                   5324:     my %servers = &get_servers($dom,'library');
                   5325:     foreach my $tryserver (keys(%servers)) {
                   5326: 	%{$personnel{$tryserver}}=();
                   5327: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5328: 					    &escape($startdate).':'.
                   5329: 					    &escape($enddate).':'.
                   5330: 					    &escape($rolelist), $tryserver))) {
                   5331: 	    my ($key,$value) = split(/\=/,$line,2);
                   5332: 	    if (($key) && ($value)) {
                   5333: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5334: 	    }
                   5335: 	}
1.662     raeburn  5336:     }
                   5337:     return %personnel;
                   5338: }
1.658     raeburn  5339: 
1.1172.2.89  raeburn  5340: sub get_active_domroles {
                   5341:     my ($dom,$roles) = @_;
                   5342:     return () unless (ref($roles) eq 'ARRAY');
                   5343:     my $now = time;
                   5344:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5345:     my %domroles;
                   5346:     foreach my $server (keys(%dompersonnel)) {
                   5347:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5348:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5349:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5350:         }
                   5351:     }
                   5352:     return %domroles;
                   5353: }
                   5354: 
1.1057    www      5355: # ----------------------------------------------------------- Interval timing 
1.149     www      5356: 
1.1153    www      5357: {
                   5358: # Caches needed for speedup of navmaps
                   5359: # We don't want to cache this for very long at all (5 seconds at most)
                   5360: # 
                   5361: # The user for whom we cache
                   5362: my $cachedkey='';
                   5363: # The cached times for this user
                   5364: my %cachedtimes=();
                   5365: # When this was last done
1.1172.2.66  raeburn  5366: my $cachedtime='';
1.1153    www      5367: 
                   5368: sub load_all_first_access {
1.1154    raeburn  5369:     my ($uname,$udom)=@_;
1.1156    www      5370:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5371:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5372:         return;
                   5373:     }
                   5374:     $cachedtime=time;
                   5375:     $cachedkey=$uname.':'.$udom;
                   5376:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5377: }
                   5378: 
1.504     albertel 5379: sub get_first_access {
1.1162    raeburn  5380:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5381:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5382:     if ($argsymb) { $symb=$argsymb; }
                   5383:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5384:     if ($argmap) { $map = $argmap; }
1.926     albertel 5385:     if ($type eq 'course') {
                   5386: 	$res='course';
                   5387:     } elsif ($type eq 'map') {
1.588     albertel 5388: 	$res=&symbread($map);
                   5389:     } else {
                   5390: 	$res=$symb;
                   5391:     }
1.1153    www      5392:     &load_all_first_access($uname,$udom);
                   5393:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5394: }
                   5395: 
                   5396: sub set_first_access {
1.1162    raeburn  5397:     my ($type,$interval)=@_;
1.790     albertel 5398:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5399:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5400:     if ($type eq 'course') {
                   5401: 	$res='course';
                   5402:     } elsif ($type eq 'map') {
1.588     albertel 5403: 	$res=&symbread($map);
                   5404:     } else {
                   5405: 	$res=$symb;
                   5406:     }
1.1153    www      5407:     $cachedkey='';
1.1162    raeburn  5408:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5409:     if ($firstaccess) {
                   5410:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5411:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5412:                  "in $courseid");
                   5413:         return 'already_set';
                   5414:     } else {
1.1162    raeburn  5415:         my $start = time;
                   5416: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5417:                           $udom,$uname);
                   5418:         if ($putres eq 'ok') {
                   5419:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5420:                  $udom,$uname); 
                   5421:             &appenv(
                   5422:                      {
                   5423:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5424:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5425:                      }
                   5426:                   );
1.1172.2.97  raeburn  5427:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5428:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5429:             }
1.1172.2.102  raeburn  5430:         } elsif ($putres ne 'refused') {
                   5431:             &logthis("Result: $putres when attempting to set first access time ".
                   5432:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5433:         }
                   5434:         return $putres;
1.505     albertel 5435:     }
                   5436:     return 'already_set';
1.504     albertel 5437: }
1.1153    www      5438: }
1.1172.2.32  raeburn  5439: 
                   5440: sub checkout {
                   5441:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5442:     my $now=time;
                   5443:     my $lonhost=$perlvar{'lonHostID'};
                   5444:     my $infostr=&escape(
                   5445:                  'CHECKOUTTOKEN&'.
                   5446:                  $tuname.'&'.
                   5447:                  $tudom.'&'.
                   5448:                  $tcrsid.'&'.
                   5449:                  $symb.'&'.
                   5450:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5451:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5452:     if ($token=~/^error\:/) {
                   5453:         &logthis("<font color=\"blue\">WARNING: ".
                   5454:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5455:                  "</font>");
                   5456:         return '';
                   5457:     }
                   5458: 
                   5459:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5460:     $token=~tr/a-z/A-Z/;
                   5461: 
                   5462:     my %infohash=('resource.0.outtoken' => $token,
                   5463:                   'resource.0.checkouttime' => $now,
                   5464:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5465: 
                   5466:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5467:        return '';
                   5468:     } else {
                   5469:         &logthis("<font color=\"blue\">WARNING: ".
                   5470:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5471:                  "</font>");
                   5472:     }
                   5473: 
                   5474:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5475:                          &escape('Checkout '.$infostr.' - '.
                   5476:                                                  $token)) ne 'ok') {
                   5477:         return '';
                   5478:     } else {
                   5479:         &logthis("<font color=\"blue\">WARNING: ".
                   5480:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5481:                  "</font>");
                   5482:     }
                   5483:     return $token;
                   5484: }
                   5485: 
                   5486: # ------------------------------------------------------------ Check in an item
                   5487: 
                   5488: sub checkin {
                   5489:     my $token=shift;
                   5490:     my $now=time;
                   5491:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5492:     $lonhost=~tr/A-Z/a-z/;
                   5493:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5494:     $dtoken=~s/\W/\_/g;
                   5495:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5496:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5497: 
                   5498:     unless (($tuname) && ($tudom)) {
                   5499:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5500:         return '';
                   5501:     }
                   5502: 
                   5503:     unless (&allowed('mgr',$tcrsid)) {
                   5504:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5505:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5506:         return '';
                   5507:     }
                   5508: 
                   5509:     my %infohash=('resource.0.intoken' => $token,
                   5510:                   'resource.0.checkintime' => $now,
                   5511:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5512: 
                   5513:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5514:        return '';
                   5515:     }
                   5516: 
                   5517:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5518:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5519:         return '';
                   5520:     }
                   5521: 
                   5522:     return ($symb,$tuname,$tudom,$tcrsid);
                   5523: }
                   5524: 
1.110     www      5525: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5526: 
                   5527: sub expirespread {
                   5528:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5529:     my $cid=$env{'request.course.id'}; 
1.110     www      5530:     if ($cid) {
                   5531:        my $now=time;
                   5532:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5533:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5534:                             $env{'course.'.$cid.'.num'}.
1.110     www      5535: 	        	    ':nohist_expirationdates:'.
                   5536:                             &escape($key).'='.$now,
1.620     albertel 5537:                             $env{'course.'.$cid.'.home'})
1.110     www      5538:     }
                   5539:     return 'ok';
1.14      www      5540: }
                   5541: 
1.109     www      5542: # ----------------------------------------------------- Devalidate Spreadsheets
                   5543: 
                   5544: sub devalidate {
1.325     www      5545:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5546:     my $cid=$env{'request.course.id'}; 
1.109     www      5547:     if ($cid) {
1.391     matthew  5548:         # delete the stored spreadsheets for
                   5549:         # - the student level sheet of this user in course's homespace
                   5550:         # - the assessment level sheet for this resource 
                   5551:         #   for this user in user's homespace
1.553     albertel 5552: 	# - current conditional state info
1.325     www      5553: 	my $key=$uname.':'.$udom.':';
1.109     www      5554:         my $status=
1.299     matthew  5555: 	    &del('nohist_calculatedsheets',
1.391     matthew  5556: 		 [$key.'studentcalc:'],
1.620     albertel 5557: 		 $env{'course.'.$cid.'.domain'},
                   5558: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5559: 		.' '.
                   5560: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5561: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5562:         unless ($status eq 'ok ok') {
                   5563:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5564:                     $uname.' at '.$udom.' for '.
1.109     www      5565: 		    $symb.': '.$status);
1.133     albertel 5566:         }
1.553     albertel 5567: 	&delenv('user.state.'.$cid);
1.109     www      5568:     }
                   5569: }
                   5570: 
1.265     albertel 5571: sub get_scalar {
                   5572:     my ($string,$end) = @_;
                   5573:     my $value;
                   5574:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5575: 	$value = $1;
                   5576:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5577: 	$value = $1;
                   5578:     }
                   5579:     return &unescape($value);
                   5580: }
                   5581: 
                   5582: sub array2str {
                   5583:   my (@array) = @_;
                   5584:   my $result=&arrayref2str(\@array);
                   5585:   $result=~s/^__ARRAY_REF__//;
                   5586:   $result=~s/__END_ARRAY_REF__$//;
                   5587:   return $result;
                   5588: }
                   5589: 
1.204     albertel 5590: sub arrayref2str {
                   5591:   my ($arrayref) = @_;
1.265     albertel 5592:   my $result='__ARRAY_REF__';
1.204     albertel 5593:   foreach my $elem (@$arrayref) {
1.265     albertel 5594:     if(ref($elem) eq 'ARRAY') {
                   5595:       $result.=&arrayref2str($elem).'&';
                   5596:     } elsif(ref($elem) eq 'HASH') {
                   5597:       $result.=&hashref2str($elem).'&';
                   5598:     } elsif(ref($elem)) {
                   5599:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5600:     } else {
                   5601:       $result.=&escape($elem).'&';
                   5602:     }
                   5603:   }
                   5604:   $result=~s/\&$//;
1.265     albertel 5605:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5606:   return $result;
                   5607: }
                   5608: 
1.168     albertel 5609: sub hash2str {
1.204     albertel 5610:   my (%hash) = @_;
                   5611:   my $result=&hashref2str(\%hash);
1.265     albertel 5612:   $result=~s/^__HASH_REF__//;
                   5613:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5614:   return $result;
                   5615: }
                   5616: 
                   5617: sub hashref2str {
                   5618:   my ($hashref)=@_;
1.265     albertel 5619:   my $result='__HASH_REF__';
1.800     albertel 5620:   foreach my $key (sort(keys(%$hashref))) {
                   5621:     if (ref($key) eq 'ARRAY') {
                   5622:       $result.=&arrayref2str($key).'=';
                   5623:     } elsif (ref($key) eq 'HASH') {
                   5624:       $result.=&hashref2str($key).'=';
                   5625:     } elsif (ref($key)) {
1.265     albertel 5626:       $result.='=';
1.800     albertel 5627:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5628:     } else {
1.1132    raeburn  5629: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5630:     }
                   5631: 
1.800     albertel 5632:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5633:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5634:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5635:       $result.=&hashref2str($hashref->{$key}).'&';
                   5636:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5637:        $result.='&';
1.800     albertel 5638:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5639:     } else {
1.800     albertel 5640:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5641:     }
                   5642:   }
1.168     albertel 5643:   $result=~s/\&$//;
1.265     albertel 5644:   $result .= '__END_HASH_REF__';
1.168     albertel 5645:   return $result;
                   5646: }
                   5647: 
                   5648: sub str2hash {
1.265     albertel 5649:     my ($string)=@_;
                   5650:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5651:     return %$hash;
                   5652: }
                   5653: 
                   5654: sub str2hashref {
1.168     albertel 5655:   my ($string) = @_;
1.265     albertel 5656: 
                   5657:   my %hash;
                   5658: 
                   5659:   if($string !~ /^__HASH_REF__/) {
                   5660:       if (! ($string eq '' || !defined($string))) {
                   5661: 	  $hash{'error'}='Not hash reference';
                   5662:       }
                   5663:       return (\%hash, $string);
                   5664:   }
                   5665: 
                   5666:   $string =~ s/^__HASH_REF__//;
                   5667: 
                   5668:   while($string !~ /^__END_HASH_REF__/) {
                   5669:       #key
                   5670:       my $key='';
                   5671:       if($string =~ /^__HASH_REF__/) {
                   5672:           ($key, $string)=&str2hashref($string);
                   5673:           if(defined($key->{'error'})) {
                   5674:               $hash{'error'}='Bad data';
                   5675:               return (\%hash, $string);
                   5676:           }
                   5677:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5678:           ($key, $string)=&str2arrayref($string);
                   5679:           if($key->[0] eq 'Array reference error') {
                   5680:               $hash{'error'}='Bad data';
                   5681:               return (\%hash, $string);
                   5682:           }
                   5683:       } else {
                   5684:           $string =~ s/^(.*?)=//;
1.267     albertel 5685: 	  $key=&unescape($1);
1.265     albertel 5686:       }
                   5687:       $string =~ s/^=//;
                   5688: 
                   5689:       #value
                   5690:       my $value='';
                   5691:       if($string =~ /^__HASH_REF__/) {
                   5692:           ($value, $string)=&str2hashref($string);
                   5693:           if(defined($value->{'error'})) {
                   5694:               $hash{'error'}='Bad data';
                   5695:               return (\%hash, $string);
                   5696:           }
                   5697:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5698:           ($value, $string)=&str2arrayref($string);
                   5699:           if($value->[0] eq 'Array reference error') {
                   5700:               $hash{'error'}='Bad data';
                   5701:               return (\%hash, $string);
                   5702:           }
                   5703:       } else {
                   5704: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5705:       }
                   5706:       $string =~ s/^&//;
                   5707: 
                   5708:       $hash{$key}=$value;
1.204     albertel 5709:   }
1.265     albertel 5710: 
                   5711:   $string =~ s/^__END_HASH_REF__//;
                   5712: 
                   5713:   return (\%hash, $string);
1.204     albertel 5714: }
                   5715: 
                   5716: sub str2array {
1.265     albertel 5717:     my ($string)=@_;
                   5718:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5719:     return @$array;
                   5720: }
                   5721: 
                   5722: sub str2arrayref {
1.204     albertel 5723:   my ($string) = @_;
1.265     albertel 5724:   my @array;
                   5725: 
                   5726:   if($string !~ /^__ARRAY_REF__/) {
                   5727:       if (! ($string eq '' || !defined($string))) {
                   5728: 	  $array[0]='Array reference error';
                   5729:       }
                   5730:       return (\@array, $string);
                   5731:   }
                   5732: 
                   5733:   $string =~ s/^__ARRAY_REF__//;
                   5734: 
                   5735:   while($string !~ /^__END_ARRAY_REF__/) {
                   5736:       my $value='';
                   5737:       if($string =~ /^__HASH_REF__/) {
                   5738:           ($value, $string)=&str2hashref($string);
                   5739:           if(defined($value->{'error'})) {
                   5740:               $array[0] ='Array reference error';
                   5741:               return (\@array, $string);
                   5742:           }
                   5743:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5744:           ($value, $string)=&str2arrayref($string);
                   5745:           if($value->[0] eq 'Array reference error') {
                   5746:               $array[0] ='Array reference error';
                   5747:               return (\@array, $string);
                   5748:           }
                   5749:       } else {
                   5750: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5751:       }
                   5752:       $string =~ s/^&//;
                   5753: 
                   5754:       push(@array, $value);
1.191     harris41 5755:   }
1.265     albertel 5756: 
                   5757:   $string =~ s/^__END_ARRAY_REF__//;
                   5758: 
                   5759:   return (\@array, $string);
1.168     albertel 5760: }
                   5761: 
1.167     albertel 5762: # -------------------------------------------------------------------Temp Store
                   5763: 
1.168     albertel 5764: sub tmpreset {
                   5765:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5766:   if (!$symb) {
                   5767:     $symb=&symbread();
1.620     albertel 5768:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5769:   }
                   5770:   $symb=escape($symb);
                   5771: 
1.620     albertel 5772:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5773:   $namespace=~s/\//\_/g;
                   5774:   $namespace=~s/\W//g;
                   5775: 
1.620     albertel 5776:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5777:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5778:   if ($domain eq 'public' && $stuname eq 'public') {
                   5779:       $stuname=$ENV{'REMOTE_ADDR'};
                   5780:   }
1.1117    foxr     5781:   my $path=LONCAPA::tempdir();
1.168     albertel 5782:   my %hash;
                   5783:   if (tie(%hash,'GDBM_File',
                   5784: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5785: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5786:     foreach my $key (keys(%hash)) {
1.180     albertel 5787:       if ($key=~ /:$symb/) {
1.168     albertel 5788: 	delete($hash{$key});
                   5789:       }
                   5790:     }
                   5791:   }
                   5792: }
                   5793: 
1.167     albertel 5794: sub tmpstore {
1.168     albertel 5795:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5796: 
                   5797:   if (!$symb) {
                   5798:     $symb=&symbread();
1.620     albertel 5799:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5800:   }
                   5801:   $symb=escape($symb);
                   5802: 
                   5803:   if (!$namespace) {
                   5804:     # I don't think we would ever want to store this for a course.
                   5805:     # it seems this will only be used if we don't have a course.
1.620     albertel 5806:     #$namespace=$env{'request.course.id'};
1.168     albertel 5807:     #if (!$namespace) {
1.620     albertel 5808:       $namespace=$env{'request.state'};
1.168     albertel 5809:     #}
                   5810:   }
                   5811:   $namespace=~s/\//\_/g;
                   5812:   $namespace=~s/\W//g;
1.620     albertel 5813:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5814:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5815:   if ($domain eq 'public' && $stuname eq 'public') {
                   5816:       $stuname=$ENV{'REMOTE_ADDR'};
                   5817:   }
1.168     albertel 5818:   my $now=time;
                   5819:   my %hash;
1.1117    foxr     5820:   my $path=LONCAPA::tempdir();
1.168     albertel 5821:   if (tie(%hash,'GDBM_File',
                   5822: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5823: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5824:     $hash{"version:$symb"}++;
                   5825:     my $version=$hash{"version:$symb"};
                   5826:     my $allkeys=''; 
                   5827:     foreach my $key (keys(%$storehash)) {
                   5828:       $allkeys.=$key.':';
1.591     albertel 5829:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5830:     }
                   5831:     $hash{"$version:$symb:timestamp"}=$now;
                   5832:     $allkeys.='timestamp';
                   5833:     $hash{"$version:keys:$symb"}=$allkeys;
                   5834:     if (untie(%hash)) {
                   5835:       return 'ok';
                   5836:     } else {
                   5837:       return "error:$!";
                   5838:     }
                   5839:   } else {
                   5840:     return "error:$!";
                   5841:   }
                   5842: }
1.167     albertel 5843: 
1.168     albertel 5844: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5845: 
1.168     albertel 5846: sub tmprestore {
                   5847:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5848: 
1.168     albertel 5849:   if (!$symb) {
                   5850:     $symb=&symbread();
1.620     albertel 5851:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5852:   }
                   5853:   $symb=escape($symb);
                   5854: 
1.620     albertel 5855:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5856: 
1.620     albertel 5857:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5858:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5859:   if ($domain eq 'public' && $stuname eq 'public') {
                   5860:       $stuname=$ENV{'REMOTE_ADDR'};
                   5861:   }
1.168     albertel 5862:   my %returnhash;
                   5863:   $namespace=~s/\//\_/g;
                   5864:   $namespace=~s/\W//g;
                   5865:   my %hash;
1.1117    foxr     5866:   my $path=LONCAPA::tempdir();
1.168     albertel 5867:   if (tie(%hash,'GDBM_File',
                   5868: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5869: 	  &GDBM_READER(),0640)) {
1.168     albertel 5870:     my $version=$hash{"version:$symb"};
                   5871:     $returnhash{'version'}=$version;
                   5872:     my $scope;
                   5873:     for ($scope=1;$scope<=$version;$scope++) {
                   5874:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5875:       my @keys=split(/:/,$vkeys);
                   5876:       my $key;
                   5877:       $returnhash{"$scope:keys"}=$vkeys;
                   5878:       foreach $key (@keys) {
1.591     albertel 5879: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5880: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5881:       }
                   5882:     }
1.168     albertel 5883:     if (!(untie(%hash))) {
                   5884:       return "error:$!";
                   5885:     }
                   5886:   } else {
                   5887:     return "error:$!";
                   5888:   }
                   5889:   return %returnhash;
1.167     albertel 5890: }
                   5891: 
1.9       www      5892: # ----------------------------------------------------------------------- Store
                   5893: 
                   5894: sub store {
1.1172.2.64  raeburn  5895:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5896:     my $home='';
                   5897: 
1.168     albertel 5898:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5899: 
1.213     www      5900:     $symb=&symbclean($symb);
1.122     albertel 5901:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5902: 
1.620     albertel 5903:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5904:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5905: 
                   5906:     &devalidate($symb,$stuname,$domain);
1.109     www      5907: 
                   5908:     $symb=escape($symb);
1.187     www      5909:     if (!$namespace) { 
1.620     albertel 5910:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5911:           return ''; 
                   5912:        } 
                   5913:     }
1.620     albertel 5914:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5915: 
                   5916:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5917:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5918: 
1.12      www      5919:     my $namevalue='';
1.800     albertel 5920:     foreach my $key (keys(%$storehash)) {
                   5921:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5922:     }
1.12      www      5923:     $namevalue=~s/\&$//;
1.187     www      5924:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5925:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5926: }
                   5927: 
1.47      www      5928: # -------------------------------------------------------------- Critical Store
                   5929: 
                   5930: sub cstore {
1.1172.2.64  raeburn  5931:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5932:     my $home='';
                   5933: 
1.168     albertel 5934:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5935: 
1.213     www      5936:     $symb=&symbclean($symb);
1.122     albertel 5937:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5938: 
1.620     albertel 5939:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5940:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5941: 
                   5942:     &devalidate($symb,$stuname,$domain);
1.109     www      5943: 
                   5944:     $symb=escape($symb);
1.187     www      5945:     if (!$namespace) { 
1.620     albertel 5946:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5947:           return ''; 
                   5948:        } 
                   5949:     }
1.620     albertel 5950:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5951: 
                   5952:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5953:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5954: 
1.47      www      5955:     my $namevalue='';
1.800     albertel 5956:     foreach my $key (keys(%$storehash)) {
                   5957:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5958:     }
1.47      www      5959:     $namevalue=~s/\&$//;
1.187     www      5960:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5961:     return critical
1.1172.2.64  raeburn  5962:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5963: }
                   5964: 
1.9       www      5965: # --------------------------------------------------------------------- Restore
                   5966: 
                   5967: sub restore {
1.124     www      5968:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5969:     my $home='';
                   5970: 
1.168     albertel 5971:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5972: 
1.122     albertel 5973:     if (!$symb) {
1.1172.2.26  raeburn  5974:         return if ($namespace eq 'courserequests');
                   5975:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5976:     } else {
1.1172.2.26  raeburn  5977:         unless ($namespace eq 'courserequests') {
                   5978:             $symb=&escape(&symbclean($symb));
                   5979:         }
1.122     albertel 5980:     }
1.188     www      5981:     if (!$namespace) { 
1.620     albertel 5982:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5983:           return ''; 
                   5984:        } 
                   5985:     }
1.620     albertel 5986:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5987:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5988:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5989:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5990: 
1.12      www      5991:     my %returnhash=();
1.800     albertel 5992:     foreach my $line (split(/\&/,$answer)) {
                   5993: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5994:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5995:     }
1.75      www      5996:     my $version;
                   5997:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5998:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5999:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6000:        }
1.75      www      6001:     }
1.13      www      6002:     return %returnhash;
1.34      www      6003: }
                   6004: 
                   6005: # ---------------------------------------------------------- Course Description
1.1118    foxr     6006: #
                   6007: #  
1.34      www      6008: 
                   6009: sub coursedescription {
1.731     albertel 6010:     my ($courseid,$args)=@_;
1.34      www      6011:     $courseid=~s/^\///;
1.49      www      6012:     $courseid=~s/\_/\//g;
1.34      www      6013:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6014:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6015:     my $normalid=$cdomain.'_'.$cnum;
                   6016:     # need to always cache even if we get errors otherwise we keep 
                   6017:     # trying and trying and trying to get the course description.
                   6018:     my %envhash=();
                   6019:     my %returnhash=();
1.731     albertel 6020:     
                   6021:     my $expiretime=600;
                   6022:     if ($env{'request.course.id'} eq $normalid) {
                   6023: 	$expiretime=120;
                   6024:     }
                   6025: 
                   6026:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6027:     if (!$args->{'freshen_cache'}
                   6028: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6029: 	foreach my $key (keys(%env)) {
                   6030: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6031: 	    my ($setting) = $1;
                   6032: 	    $returnhash{$setting} = $env{$key};
                   6033: 	}
                   6034: 	return %returnhash;
                   6035:     }
                   6036: 
1.1118    foxr     6037:     # get the data again
                   6038: 
1.731     albertel 6039:     if (!$args->{'one_time'}) {
                   6040: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6041:     }
1.811     albertel 6042: 
1.34      www      6043:     if ($chome ne 'no_host') {
1.302     albertel 6044:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6045:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6046: 	   my $username = $env{'user.name'}; # Defult username
                   6047: 	   if(defined $args->{'user'}) {
                   6048: 	       $username = $args->{'user'};
                   6049: 	   }
1.129     albertel 6050:            $returnhash{'home'}= $chome;
                   6051: 	   $returnhash{'domain'} = $cdomain;
                   6052: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6053:            if (!defined($returnhash{'type'})) {
                   6054:                $returnhash{'type'} = 'Course';
                   6055:            }
1.130     albertel 6056:            while (my ($name,$value) = each %returnhash) {
1.53      www      6057:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6058:            }
1.270     www      6059:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6060:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6061: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6062:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6063:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6064:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6065:        }
                   6066:     }
1.731     albertel 6067:     if (!$args->{'one_time'}) {
1.949     raeburn  6068: 	&appenv(\%envhash);
1.731     albertel 6069:     }
1.302     albertel 6070:     return %returnhash;
1.461     www      6071: }
                   6072: 
1.1080    raeburn  6073: sub update_released_required {
                   6074:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6075:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6076:         $cid = $env{'request.course.id'};
                   6077:         $cdom = $env{'course.'.$cid.'.domain'};
                   6078:         $cnum = $env{'course.'.$cid.'.num'};
                   6079:         $chome = $env{'course.'.$cid.'.home'};
                   6080:     }
                   6081:     if ($needsrelease) {
                   6082:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6083:         my $needsupdate;
                   6084:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6085:             $needsupdate = 1;
                   6086:         } else {
                   6087:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6088:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6089:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6090:                 $needsupdate = 1;
                   6091:             }
                   6092:         }
                   6093:         if ($needsupdate) {
                   6094:             my %needshash = (
                   6095:                              'internal.releaserequired' => $needsrelease,
                   6096:                             );
                   6097:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6098:             if ($putresult eq 'ok') {
                   6099:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6100:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6101:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6102:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6103:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6104:                 }
                   6105:             }
                   6106:         }
                   6107:     }
                   6108:     return;
                   6109: }
                   6110: 
1.461     www      6111: # -------------------------------------------------See if a user is privileged
                   6112: 
                   6113: sub privileged {
1.1172.2.23  raeburn  6114:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6115:     my $now = time;
1.1172.2.23  raeburn  6116:     my $roles;
                   6117:     if (ref($possroles) eq 'ARRAY') {
                   6118:         $roles = $possroles;
                   6119:     } else {
                   6120:         $roles = ['dc','su'];
                   6121:     }
                   6122:     if (ref($possdomains) eq 'ARRAY') {
                   6123:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6124:         foreach my $dom (@{$possdomains}) {
                   6125:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6126:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6127:                 foreach my $role (@{$roles}) {
                   6128:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6129:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6130:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6131:                             return 1 unless (($end && $end < $now) ||
                   6132:                                              ($start && $start > $now));
                   6133:                         }
                   6134:                     }
                   6135:                 }
                   6136:             }
                   6137:         }
                   6138:     } else {
                   6139:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6140:         my $now = time;
1.1170    droeschl 6141: 
1.1172.2.58  raeburn  6142:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6143:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6144:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6145:                 return 1 unless ($tend && $tend < $now)
                   6146:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6147:             }
1.1172.2.23  raeburn  6148:         }
                   6149:     }
1.461     www      6150:     return 0;
1.9       www      6151: }
1.1       albertel 6152: 
1.1172.2.23  raeburn  6153: sub privileged_by_domain {
                   6154:     my ($domains,$roles) = @_;
                   6155:     my %privileged = ();
                   6156:     my $cachetime = 60*60*24;
                   6157:     my $now = time;
                   6158:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6159:         return %privileged;
                   6160:     }
                   6161:     foreach my $dom (@{$domains}) {
                   6162:         next if (ref($privileged{$dom}) eq 'HASH');
                   6163:         my $needroles;
                   6164:         foreach my $role (@{$roles}) {
                   6165:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6166:             if (defined($cached)) {
                   6167:                 if (ref($result) eq 'HASH') {
                   6168:                     $privileged{$dom}{$role} = $result;
                   6169:                 }
                   6170:             } else {
                   6171:                 $needroles = 1;
                   6172:             }
                   6173:         }
                   6174:         if ($needroles) {
                   6175:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6176:             $privileged{$dom} = {};
                   6177:             foreach my $server (keys(%dompersonnel)) {
                   6178:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6179:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6180:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6181:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6182:                         next if ($end && $end < $now);
                   6183:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6184:                             $dompersonnel{$server}{$item};
                   6185:                     }
                   6186:                 }
                   6187:             }
                   6188:             if (ref($privileged{$dom}) eq 'HASH') {
                   6189:                 foreach my $role (@{$roles}) {
                   6190:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6191:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6192:                     } else {
                   6193:                         my %hash = ();
                   6194:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6195:                     }
                   6196:                 }
                   6197:             }
                   6198:         }
                   6199:     }
                   6200:     return %privileged;
                   6201: }
                   6202: 
1.103     harris41 6203: # -------------------------------------------------------- Get user privileges
1.11      www      6204: 
                   6205: sub rolesinit {
1.1169    droeschl 6206:     my ($domain, $username) = @_;
                   6207:     my %userroles = ('user.login.time' => time);
                   6208:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6209: 
                   6210:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6211:     # also, blocking can be triggered by an activating timer
                   6212:     # it's saved in the user's %env.
                   6213:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6214:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6215:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6216:         %timerintchk, %timerintenv);
                   6217: 
1.1162    raeburn  6218:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6219:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6220:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6221:     }
1.1169    droeschl 6222: 
1.1162    raeburn  6223:     foreach my $key (keys(%timerinterval)) {
                   6224:         my ($cid,$rest) = split(/\0/,$key);
                   6225:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6226:     }
1.1169    droeschl 6227: 
1.11      www      6228:     my %allroles=();
1.1162    raeburn  6229:     my %allgroups=();
1.11      www      6230: 
1.1172.2.58  raeburn  6231:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6232:         my $role = $rolesdump{$area};
                   6233:         $area =~ s/\_\w\w$//;
                   6234: 
                   6235:         my ($trole, $tend, $tstart, $group_privs);
                   6236: 
                   6237:         if ($role =~ /^cr/) {
                   6238:         # Custom role, defined by a user 
                   6239:         # e.g., user.role.cr/msu/smith/mynewrole
                   6240:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6241:                 $trole = $1;
                   6242:                 ($tend, $tstart) = split('_', $2);
                   6243:             } else {
                   6244:                 $trole = $role;
                   6245:             }
                   6246:         } elsif ($role =~ m|^gr/|) {
                   6247:         # Role of member in a group, defined within a course/community
                   6248:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6249:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6250:             next if $tstart eq '-1';
                   6251:             ($trole, $group_privs) = split(/\//, $trole);
                   6252:             $group_privs = &unescape($group_privs);
                   6253:         } else {
                   6254:         # Just a normal role, defined in roles.tab
                   6255:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6256:         }
                   6257: 
                   6258:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6259:                  $username);
                   6260:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6261: 
                   6262:         # role expired or not available yet?
                   6263:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6264:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6265: 
                   6266:         next if $area eq '' or $trole eq '';
                   6267: 
                   6268:         my $spec = "$trole.$area";
                   6269:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6270: 
                   6271:         if ($trole =~ /^cr\//) {
                   6272:         # Custom role, defined by a user
                   6273:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6274:         } elsif ($trole eq 'gr') {
                   6275:         # Role of a member in a group, defined within a course/community
                   6276:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6277:             next;
                   6278:         } else {
                   6279:         # Normal role, defined in roles.tab
                   6280:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6281:         }
                   6282: 
                   6283:         my $cid = $tdomain.'_'.$trest;
                   6284:         unless ($firstaccchk{$cid}) {
                   6285:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6286:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6287:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6288:                         $coursetimerstarts{$cid}{$item}; 
                   6289:                 }
                   6290:             }
                   6291:             $firstaccchk{$cid} = 1;
                   6292:         }
                   6293:         unless ($timerintchk{$cid}) {
                   6294:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6295:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6296:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6297:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6298:                 }
1.12      www      6299:             }
1.1169    droeschl 6300:             $timerintchk{$cid} = 1;
1.191     harris41 6301:         }
1.11      www      6302:     }
1.1169    droeschl 6303: 
1.1172.2.91  raeburn  6304:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6305:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6306:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6307:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6308: 
1.1162    raeburn  6309:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6310: }
                   6311: 
1.567     raeburn  6312: sub set_arearole {
1.1172.2.19  raeburn  6313:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6314:     unless ($nolog) {
1.567     raeburn  6315: # log the associated role with the area
1.1172.2.19  raeburn  6316:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6317:     }
1.743     albertel 6318:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6319: }
                   6320: 
                   6321: sub custom_roleprivs {
                   6322:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6323:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6324:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6325:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6326:         my ($rdummy,$roledef)=
                   6327:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6328:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6329:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6330:             if (defined($syspriv)) {
1.1043    raeburn  6331:                 if ($trest =~ /^$match_community$/) {
                   6332:                     $syspriv =~ s/bre\&S//; 
                   6333:                 }
1.567     raeburn  6334:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6335:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6336:             }
                   6337:             if ($tdomain ne '') {
                   6338:                 if (defined($dompriv)) {
                   6339:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6340:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6341:                 }
                   6342:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6343:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6344:                         my $rolename = $1;
                   6345:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6346:                     }
1.567     raeburn  6347:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6348:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6349:                 }
                   6350:             }
                   6351:         }
                   6352:     }
                   6353: }
                   6354: 
1.1172.2.89  raeburn  6355: sub course_adhocrole_privs {
                   6356:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6357:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6358:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6359:         my (%currprivs,%storeprivs);
                   6360:         foreach my $item (split(/:/,$coursepriv)) {
                   6361:             my ($priv,$restrict) = split(/\&/,$item);
                   6362:             $currprivs{$priv} = $restrict;
                   6363:         }
                   6364:         my (%possadd,%possremove,%full);
                   6365:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6366:             my ($priv,$restrict)=split(/\&/,$item);
                   6367:             $full{$priv} = $restrict;
                   6368:         }
                   6369:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6370:              next if ($item eq '');
                   6371:              my ($rule,$rest) = split(/=/,$item);
                   6372:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6373:              foreach my $priv (split(/:/,$rest)) {
                   6374:                  if ($priv ne '') {
                   6375:                      if ($rule eq 'off') {
                   6376:                          $possremove{$priv} = 1;
                   6377:                      } else {
                   6378:                          $possadd{$priv} = 1;
                   6379:                      }
                   6380:                  }
                   6381:              }
                   6382:          }
                   6383:          foreach my $priv (sort(keys(%full))) {
                   6384:              if (exists($currprivs{$priv})) {
                   6385:                  unless (exists($possremove{$priv})) {
                   6386:                      $storeprivs{$priv} = $currprivs{$priv};
                   6387:                  }
                   6388:              } elsif (exists($possadd{$priv})) {
                   6389:                  $storeprivs{$priv} = $full{$priv};
                   6390:              }
                   6391:          }
                   6392:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6393:      }
                   6394:      return $coursepriv;
                   6395: }
                   6396: 
1.678     raeburn  6397: sub group_roleprivs {
                   6398:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6399:     my $access = 1;
                   6400:     my $now = time;
                   6401:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6402:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6403:     if ($access) {
1.811     albertel 6404:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6405:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6406:     }
                   6407: }
1.567     raeburn  6408: 
                   6409: sub standard_roleprivs {
                   6410:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6411:     if (defined($pr{$trole.':s'})) {
                   6412:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6413:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6414:     }
                   6415:     if ($tdomain ne '') {
                   6416:         if (defined($pr{$trole.':d'})) {
                   6417:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6418:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6419:         }
                   6420:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6421:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6422:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6423:         }
                   6424:     }
                   6425: }
                   6426: 
                   6427: sub set_userprivs {
1.1064    raeburn  6428:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6429:     my $author=0;
                   6430:     my $adv=0;
1.1172.2.91  raeburn  6431:     my $rar=0;
1.678     raeburn  6432:     my %grouproles = ();
                   6433:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6434:         my @groupkeys; 
1.1000    raeburn  6435:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6436:             push(@groupkeys,$role);
                   6437:         }
                   6438:         if (ref($groups_roles) eq 'HASH') {
                   6439:             foreach my $key (keys(%{$groups_roles})) {
                   6440:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6441:                     push(@groupkeys,$key);
                   6442:                 }
                   6443:             }
                   6444:         }
                   6445:         if (@groupkeys > 0) {
                   6446:             foreach my $role (@groupkeys) {
                   6447:                 my ($trole,$area,$sec,$extendedarea);
                   6448:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6449:                     $trole = $1;
                   6450:                     $area = $2;
                   6451:                     $sec = $3;
                   6452:                     $extendedarea = $area.$sec;
                   6453:                     if (exists($$allgroups{$area})) {
                   6454:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6455:                             my $spec = $trole.'.'.$extendedarea;
                   6456:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6457:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6458:                         }
1.678     raeburn  6459:                     }
                   6460:                 }
                   6461:             }
                   6462:         }
                   6463:     }
1.800     albertel 6464:     foreach my $group (keys(%grouproles)) {
                   6465:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6466:     }
1.800     albertel 6467:     foreach my $role (keys(%{$allroles})) {
                   6468:         my %thesepriv;
1.941     raeburn  6469:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6470:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6471:             if ($item ne '') {
                   6472:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6473:                 if ($restrictions eq '') {
                   6474:                     $thesepriv{$privilege}='F';
                   6475:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6476:                     $thesepriv{$privilege}.=$restrictions;
                   6477:                 }
                   6478:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6479:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6480:             }
                   6481:         }
                   6482:         my $thesestr='';
1.1104    raeburn  6483:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6484: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6485: 	}
                   6486:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6487:     }
1.1172.2.91  raeburn  6488:     return ($author,$adv,$rar);
1.567     raeburn  6489: }
                   6490: 
1.994     raeburn  6491: sub role_status {
1.1104    raeburn  6492:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6493:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6494:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6495:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6496:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6497:             $$where = '/'.$two;
1.994     raeburn  6498:             $$trolecode=$$role.'.'.$$where;
                   6499:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6500:             $$tstatus='is';
1.1104    raeburn  6501:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6502:                 $$tstatus='future';
1.1034    raeburn  6503:                 if ($$tstart<$now) {
                   6504:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6505:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6506:                             my (%allroles,%allgroups,$group_privs,
                   6507:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6508:                             my %userroles = (
                   6509:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6510:                             );
1.1064    raeburn  6511:                             @rolecodes = ('cm'); 
1.1002    raeburn  6512:                             my $spec=$$role.'.'.$$where;
                   6513:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6514:                             if ($$role =~ /^cr\//) {
                   6515:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6516:                                 push(@rolecodes,'cr');
1.1002    raeburn  6517:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6518:                                 push(@rolecodes,$$role);
1.1002    raeburn  6519:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6520:                                                     $env{'user.name'});
1.1064    raeburn  6521:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6522:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6523:                                 $group_privs = &unescape($group_privs);
                   6524:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6525:                                 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  6526:                                 &get_groups_roles($tdomain,$trest,
                   6527:                                                   \%course_roles,\@rolecodes,
                   6528:                                                   \%groups_roles);
1.1002    raeburn  6529:                             } else {
1.1064    raeburn  6530:                                 push(@rolecodes,$$role);
1.1002    raeburn  6531:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6532:                             }
1.1172.2.91  raeburn  6533:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6534:                                                                    \%groups_roles);
1.1064    raeburn  6535:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6536:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6537:                         }
                   6538:                     }
1.1034    raeburn  6539:                     $$tstatus = 'is';
1.1002    raeburn  6540:                 }
1.994     raeburn  6541:             }
                   6542:             if ($$tend) {
1.1104    raeburn  6543:                 if ($$tend<$update) {
1.994     raeburn  6544:                     $$tstatus='expired';
                   6545:                 } elsif ($$tend<$now) {
                   6546:                     $$tstatus='will_not';
                   6547:                 }
                   6548:             }
                   6549:         }
                   6550:     }
                   6551: }
                   6552: 
1.1104    raeburn  6553: sub get_groups_roles {
                   6554:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6555:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6556:                   (ref($rolecodes) eq 'ARRAY') && 
                   6557:                   (ref($groups_roles) eq 'HASH')); 
                   6558:     if (keys(%{$cdom_courseroles}) > 0) {
                   6559:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6560:         if ($cdom ne '' && $cnum ne '') {
                   6561:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6562:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6563:                     my $crsrole = $1;
                   6564:                     my $crssec = $2;
                   6565:                     if ($crsrole =~ /^cr/) {
                   6566:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6567:                             push(@{$rolecodes},'cr');
                   6568:                         }
                   6569:                     } else {
                   6570:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6571:                             push(@{$rolecodes},$crsrole);
                   6572:                         }
                   6573:                     }
                   6574:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6575:                     if ($crssec ne '') {
                   6576:                         $rolekey .= "/$crssec";
                   6577:                     }
                   6578:                     $rolekey .= './';
                   6579:                     $groups_roles->{$rolekey} = $rolecodes;
                   6580:                 }
                   6581:             }
                   6582:         }
                   6583:     }
                   6584:     return;
                   6585: }
                   6586: 
                   6587: sub delete_env_groupprivs {
                   6588:     my ($where,$courseroles,$possroles) = @_;
                   6589:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6590:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6591:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6592:         %{$courseroles->{$udom}} =
                   6593:             &get_my_roles('','','userroles',['active'],
                   6594:                           $possroles,[$udom],1);
                   6595:     }
                   6596:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6597:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6598:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6599:             my $area = '/'.$cdom.'/'.$cnum;
                   6600:             my $privkey = "user.priv.$crsrole.$area";
                   6601:             if ($crssec ne '') {
                   6602:                 $privkey .= '/'.$crssec;
                   6603:             }
                   6604:             $privkey .= ".$area/$group";
                   6605:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6606:         }
                   6607:     }
                   6608:     return;
                   6609: }
                   6610: 
1.994     raeburn  6611: sub check_adhoc_privs {
1.1172.2.86  raeburn  6612:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6613:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6614:     if ($sec) {
                   6615:         $cckey .= '/'.$sec;
                   6616:     }
1.1172.2.9  raeburn  6617:     my $setprivs;
1.994     raeburn  6618:     if ($env{$cckey}) {
                   6619:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6620:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6621:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6622:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6623:             $setprivs = 1;
1.994     raeburn  6624:         }
                   6625:     } else {
1.1172.2.87  raeburn  6626:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6627:         $setprivs = 1;
1.994     raeburn  6628:     }
1.1172.2.9  raeburn  6629:     return $setprivs;
1.994     raeburn  6630: }
                   6631: 
                   6632: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6633: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6634:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6635:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6636:     if ($sec ne '') {
                   6637:         $area .= '/'.$sec;
                   6638:     }
1.994     raeburn  6639:     my $spec = $role.'.'.$area;
                   6640:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6641:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6642:     my %rolehash = ();
1.1172.2.89  raeburn  6643:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6644:         my $rolename = $1;
1.1172.2.84  raeburn  6645:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6646:         my %domdef = &get_domain_defaults($dcdom);
                   6647:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6648:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6649:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6650:             }
                   6651:         }
1.1172.2.84  raeburn  6652:     } else {
                   6653:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6654:     }
1.1172.2.91  raeburn  6655:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6656:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6657:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6658:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6659:         &appenv( {'request.role'        => $spec,
                   6660:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6661:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6662:                  }
                   6663:                );
                   6664:         my $tadv=0;
                   6665:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6666:         &appenv({'request.role.adv'    => $tadv});
                   6667:     }
1.994     raeburn  6668: }
                   6669: 
1.12      www      6670: # --------------------------------------------------------------- get interface
                   6671: 
                   6672: sub get {
1.131     albertel 6673:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6674:    my $items='';
1.800     albertel 6675:    foreach my $item (@$storearr) {
                   6676:        $items.=&escape($item).'&';
1.191     harris41 6677:    }
1.12      www      6678:    $items=~s/\&$//;
1.620     albertel 6679:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6680:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6681:    my $uhome=&homeserver($uname,$udomain);
                   6682: 
1.133     albertel 6683:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6684:    my @pairs=split(/\&/,$rep);
1.273     albertel 6685:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6686:      return @pairs;
                   6687:    }
1.15      www      6688:    my %returnhash=();
1.42      www      6689:    my $i=0;
1.800     albertel 6690:    foreach my $item (@$storearr) {
                   6691:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6692:       $i++;
1.191     harris41 6693:    }
1.15      www      6694:    return %returnhash;
1.27      www      6695: }
                   6696: 
                   6697: # --------------------------------------------------------------- del interface
                   6698: 
                   6699: sub del {
1.133     albertel 6700:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6701:    my $items='';
1.800     albertel 6702:    foreach my $item (@$storearr) {
                   6703:        $items.=&escape($item).'&';
1.191     harris41 6704:    }
1.984     neumanie 6705: 
1.27      www      6706:    $items=~s/\&$//;
1.620     albertel 6707:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6708:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6709:    my $uhome=&homeserver($uname,$udomain);
                   6710:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6711: }
                   6712: 
                   6713: # -------------------------------------------------------------- dump interface
                   6714: 
1.1172.2.22  raeburn  6715: sub unserialize {
                   6716:     my ($rep, $escapedkeys) = @_;
                   6717: 
                   6718:     return {} if $rep =~ /^error/;
                   6719: 
                   6720:     my %returnhash=();
                   6721:     foreach my $item (split(/\&/,$rep)) {
                   6722:         my ($key, $value) = split(/=/, $item, 2);
                   6723:         $key = unescape($key) unless $escapedkeys;
                   6724:         next if $key =~ /^error: 2 /;
                   6725:         $returnhash{$key} = &thaw_unescape($value);
                   6726:     }
                   6727:     return \%returnhash;
                   6728: }
                   6729: 
                   6730: # see Lond::dump_with_regexp
                   6731: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6732: sub dump {
1.1172.2.22  raeburn  6733:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6734:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6735:     if (!$uname) { $uname=$env{'user.name'}; }
                   6736:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6737: 
1.1172.2.55  raeburn  6738:     if ($regexp) {
                   6739:         $regexp=&escape($regexp);
                   6740:     } else {
                   6741:         $regexp='.';
                   6742:     }
1.1172.2.22  raeburn  6743:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6744:         # user is hosted on this machine
1.1172.2.55  raeburn  6745:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6746:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6747:         return %{&unserialize($reply, $escapedkeys)};
                   6748:     }
1.1166    raeburn  6749:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6750:     my @pairs=split(/\&/,$rep);
                   6751:     my %returnhash=();
1.1098    foxr     6752:     if (!($rep =~ /^error/ )) {
                   6753: 	foreach my $item (@pairs) {
                   6754: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6755:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6756: 	    next if ($key =~ /^error: 2 /);
                   6757: 	    $returnhash{$key}=&thaw_unescape($value);
                   6758: 	}
1.755     albertel 6759:     }
                   6760:     return %returnhash;
1.407     www      6761: }
                   6762: 
1.1098    foxr     6763: 
1.717     albertel 6764: # --------------------------------------------------------- dumpstore interface
                   6765: 
                   6766: sub dumpstore {
                   6767:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6768:    # same as dump but keys must be escaped. They may contain colon separated
                   6769:    # lists of values that may themself contain colons (e.g. symbs).
                   6770:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6771: }
                   6772: 
1.407     www      6773: # -------------------------------------------------------------- keys interface
                   6774: 
                   6775: sub getkeys {
                   6776:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6777:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6778:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6779:    my $uhome=&homeserver($uname,$udomain);
                   6780:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6781:    my @keyarray=();
1.800     albertel 6782:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6783:       next if ($key =~ /^error: 2 /);
1.800     albertel 6784:       push(@keyarray,&unescape($key));
1.407     www      6785:    }
                   6786:    return @keyarray;
1.318     matthew  6787: }
                   6788: 
1.319     matthew  6789: # --------------------------------------------------------------- currentdump
                   6790: sub currentdump {
1.328     matthew  6791:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6792:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6793:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6794:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6795:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6796:    my $rep;
                   6797: 
                   6798:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6799:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6800:                    $courseid)));
                   6801:    } else {
                   6802:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6803:    }
                   6804: 
1.318     matthew  6805:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6806:    #
1.318     matthew  6807:    my %returnhash=();
1.319     matthew  6808:    #
                   6809:    if ($rep eq "unknown_cmd") { 
                   6810:        # an old lond will not know currentdump
                   6811:        # Do a dump and make it look like a currentdump
1.822     albertel 6812:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6813:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6814:        my %hash = @tmp;
                   6815:        @tmp=();
1.424     matthew  6816:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6817:    } else {
                   6818:        my @pairs=split(/\&/,$rep);
1.800     albertel 6819:        foreach my $pair (@pairs) {
                   6820:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6821:            my ($symb,$param) = split(/:/,$key);
                   6822:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6823:                                                         &thaw_unescape($value);
1.319     matthew  6824:        }
1.191     harris41 6825:    }
1.12      www      6826:    return %returnhash;
1.424     matthew  6827: }
                   6828: 
                   6829: sub convert_dump_to_currentdump{
                   6830:     my %hash = %{shift()};
                   6831:     my %returnhash;
                   6832:     # Code ripped from lond, essentially.  The only difference
                   6833:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6834:     # we might run in to problems with parameter names =~ /^v\./
                   6835:     while (my ($key,$value) = each(%hash)) {
                   6836:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6837: 	$symb  = &unescape($symb);
                   6838: 	$param = &unescape($param);
1.424     matthew  6839:         next if ($v eq 'version' || $symb eq 'keys');
                   6840:         next if (exists($returnhash{$symb}) &&
                   6841:                  exists($returnhash{$symb}->{$param}) &&
                   6842:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6843:         $returnhash{$symb}->{$param}=$value;
                   6844:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6845:     }
                   6846:     #
                   6847:     # Remove all of the keys in the hashes which keep track of
                   6848:     # the version of the parameter.
                   6849:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6850:         # use a foreach because we are going to delete from the hash.
                   6851:         foreach my $key (keys(%$param_hash)) {
                   6852:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6853:         }
                   6854:     }
                   6855:     return \%returnhash;
1.12      www      6856: }
                   6857: 
1.627     albertel 6858: # ------------------------------------------------------ critical inc interface
                   6859: 
                   6860: sub cinc {
                   6861:     return &inc(@_,'critical');
                   6862: }
                   6863: 
1.449     matthew  6864: # --------------------------------------------------------------- inc interface
                   6865: 
                   6866: sub inc {
1.627     albertel 6867:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6868:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6869:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6870:     my $uhome=&homeserver($uname,$udomain);
                   6871:     my $items='';
                   6872:     if (! ref($store)) {
                   6873:         # got a single value, so use that instead
                   6874:         $items = &escape($store).'=&';
                   6875:     } elsif (ref($store) eq 'SCALAR') {
                   6876:         $items = &escape($$store).'=&';        
                   6877:     } elsif (ref($store) eq 'ARRAY') {
                   6878:         $items = join('=&',map {&escape($_);} @{$store});
                   6879:     } elsif (ref($store) eq 'HASH') {
                   6880:         while (my($key,$value) = each(%{$store})) {
                   6881:             $items.= &escape($key).'='.&escape($value).'&';
                   6882:         }
                   6883:     }
                   6884:     $items=~s/\&$//;
1.627     albertel 6885:     if ($critical) {
                   6886: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6887:     } else {
                   6888: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6889:     }
1.449     matthew  6890: }
                   6891: 
1.12      www      6892: # --------------------------------------------------------------- put interface
                   6893: 
                   6894: sub put {
1.134     albertel 6895:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6896:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6897:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6898:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6899:    my $items='';
1.800     albertel 6900:    foreach my $item (keys(%$storehash)) {
                   6901:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6902:    }
1.12      www      6903:    $items=~s/\&$//;
1.134     albertel 6904:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6905: }
                   6906: 
1.631     albertel 6907: # ------------------------------------------------------------ newput interface
                   6908: 
                   6909: sub newput {
                   6910:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6911:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6912:    if (!$uname) { $uname=$env{'user.name'}; }
                   6913:    my $uhome=&homeserver($uname,$udomain);
                   6914:    my $items='';
                   6915:    foreach my $key (keys(%$storehash)) {
                   6916:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6917:    }
                   6918:    $items=~s/\&$//;
                   6919:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6920: }
                   6921: 
                   6922: # ---------------------------------------------------------  putstore interface
                   6923: 
1.524     raeburn  6924: sub putstore {
1.1172.2.59  raeburn  6925:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6926:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6927:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6928:    my $uhome=&homeserver($uname,$udomain);
                   6929:    my $items='';
1.715     albertel 6930:    foreach my $key (keys(%$storehash)) {
                   6931:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6932:    }
1.715     albertel 6933:    $items=~s/\&$//;
1.716     albertel 6934:    my $esc_symb=&escape($symb);
                   6935:    my $esc_v=&escape($version);
1.715     albertel 6936:    my $reply =
1.716     albertel 6937:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6938: 	      $uhome);
1.1172.2.59  raeburn  6939:    if (($tolog) && ($reply eq 'ok')) {
                   6940:        my $namevalue='';
                   6941:        foreach my $key (keys(%{$storehash})) {
                   6942:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6943:        }
                   6944:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6945:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6946:                      '&version='.$esc_v.
                   6947:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6948:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6949:    }
1.715     albertel 6950:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6951:        # gfall back to way things use to be done
1.715     albertel 6952:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6953: 			    $uname);
1.524     raeburn  6954:    }
1.715     albertel 6955:    return $reply;
                   6956: }
                   6957: 
                   6958: sub old_putstore {
1.716     albertel 6959:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6960:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6961:     if (!$uname) { $uname=$env{'user.name'}; }
                   6962:     my $uhome=&homeserver($uname,$udomain);
                   6963:     my %newstorehash;
1.800     albertel 6964:     foreach my $item (keys(%$storehash)) {
                   6965: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6966: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6967:     }
                   6968:     my $items='';
                   6969:     my %allitems = ();
1.800     albertel 6970:     foreach my $item (keys(%newstorehash)) {
                   6971: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6972: 	    my $key = $1.':keys:'.$2;
                   6973: 	    $allitems{$key} .= $3.':';
                   6974: 	}
1.800     albertel 6975: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6976:     }
1.800     albertel 6977:     foreach my $item (keys(%allitems)) {
                   6978: 	$allitems{$item} =~ s/\:$//;
                   6979: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6980:     }
                   6981:     $items=~s/\&$//;
                   6982:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6983: }
                   6984: 
1.47      www      6985: # ------------------------------------------------------ critical put interface
                   6986: 
                   6987: sub cput {
1.134     albertel 6988:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6989:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6990:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6991:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6992:    my $items='';
1.800     albertel 6993:    foreach my $item (keys(%$storehash)) {
                   6994:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6995:    }
1.47      www      6996:    $items=~s/\&$//;
1.134     albertel 6997:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6998: }
                   6999: 
                   7000: # -------------------------------------------------------------- eget interface
                   7001: 
                   7002: sub eget {
1.133     albertel 7003:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7004:    my $items='';
1.800     albertel 7005:    foreach my $item (@$storearr) {
                   7006:        $items.=&escape($item).'&';
1.191     harris41 7007:    }
1.12      www      7008:    $items=~s/\&$//;
1.620     albertel 7009:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7010:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7011:    my $uhome=&homeserver($uname,$udomain);
                   7012:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7013:    my @pairs=split(/\&/,$rep);
                   7014:    my %returnhash=();
1.42      www      7015:    my $i=0;
1.800     albertel 7016:    foreach my $item (@$storearr) {
                   7017:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7018:       $i++;
1.191     harris41 7019:    }
1.12      www      7020:    return %returnhash;
                   7021: }
                   7022: 
1.667     albertel 7023: # ------------------------------------------------------------ tmpput interface
                   7024: sub tmpput {
1.802     raeburn  7025:     my ($storehash,$server,$context)=@_;
1.667     albertel 7026:     my $items='';
1.800     albertel 7027:     foreach my $item (keys(%$storehash)) {
                   7028: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7029:     }
                   7030:     $items=~s/\&$//;
1.802     raeburn  7031:     if (defined($context)) {
                   7032:         $items .= ':'.&escape($context);
                   7033:     }
1.667     albertel 7034:     return &reply("tmpput:$items",$server);
                   7035: }
                   7036: 
                   7037: # ------------------------------------------------------------ tmpget interface
                   7038: sub tmpget {
1.688     albertel 7039:     my ($token,$server)=@_;
                   7040:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7041:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7042:     my %returnhash;
1.1172.2.85  raeburn  7043:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7044:         return %returnhash;
                   7045:     }
1.667     albertel 7046:     foreach my $item (split(/\&/,$rep)) {
                   7047: 	my ($key,$value)=split(/=/,$item);
                   7048: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7049:     }
                   7050:     return %returnhash;
                   7051: }
                   7052: 
1.1113    raeburn  7053: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7054: sub tmpdel {
                   7055:     my ($token,$server)=@_;
                   7056:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7057:     return &reply("tmpdel:$token",$server);
                   7058: }
                   7059: 
1.1172.2.13  raeburn  7060: # ------------------------------------------------------------ get_timebased_id
                   7061: 
                   7062: sub get_timebased_id {
                   7063:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7064:         $maxtries) = @_;
                   7065:     my ($newid,$error,$dellock);
                   7066:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7067:         return ('','ok','invalid call to get suffix');
                   7068:     }
                   7069: 
                   7070: # set defaults for any optional args for which values were not supplied
                   7071:     if ($who eq '') {
                   7072:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7073:     }
                   7074:     if (!$locktries) {
                   7075:         $locktries = 3;
                   7076:     }
                   7077:     if (!$maxtries) {
                   7078:         $maxtries = 10;
                   7079:     }
                   7080: 
                   7081:     if (($cdom eq '') || ($cnum eq '')) {
                   7082:         if ($env{'request.course.id'}) {
                   7083:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7084:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7085:         }
                   7086:         if (($cdom eq '') || ($cnum eq '')) {
                   7087:             return ('','ok','call to get suffix not in course context');
                   7088:         }
                   7089:     }
                   7090: 
                   7091: # construct locking item
                   7092:     my $lockhash = {
                   7093:                       $prefix."\0".'locked_'.$keyid => $who,
                   7094:                    };
                   7095:     my $tries = 0;
                   7096: 
                   7097: # attempt to get lock on nohist_$namespace file
                   7098:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7099:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7100:         $tries ++;
                   7101:         sleep 1;
                   7102:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7103:     }
                   7104: 
                   7105: # attempt to get unique identifier, based on current timestamp
                   7106:     if ($gotlock eq 'ok') {
                   7107:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7108:         my $id = time;
                   7109:         $newid = $id;
1.1172.2.56  raeburn  7110:         if ($idtype eq 'addcode') {
                   7111:             $newid .= &sixnum_code();
                   7112:         }
1.1172.2.13  raeburn  7113:         my $idtries = 0;
                   7114:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7115:             if ($idtype eq 'concat') {
                   7116:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7117:             } elsif ($idtype eq 'addcode') {
                   7118:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7119:             } else {
                   7120:                 $newid ++;
                   7121:             }
                   7122:             $idtries ++;
                   7123:         }
                   7124:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7125:             my %new_item =  (
                   7126:                               $prefix."\0".$newid => $who,
                   7127:                             );
                   7128:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7129:                                                  $cdom,$cnum);
                   7130:             if ($putresult ne 'ok') {
                   7131:                 undef($newid);
                   7132:                 $error = 'error saving new item: '.$putresult;
                   7133:             }
                   7134:         } else {
1.1172.2.56  raeburn  7135:              undef($newid);
1.1172.2.13  raeburn  7136:              $error = ('error: no unique suffix available for the new item ');
                   7137:         }
                   7138: #  remove lock
                   7139:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7140:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7141:     } else {
                   7142:         $error = "error: could not obtain lockfile\n";
                   7143:         $dellock = 'ok';
1.1172.2.58  raeburn  7144:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7145:             $dellock = 'nolock';
                   7146:         }
1.1172.2.13  raeburn  7147:     }
                   7148:     return ($newid,$dellock,$error);
                   7149: }
                   7150: 
1.1172.2.56  raeburn  7151: sub sixnum_code {
                   7152:     my $code;
                   7153:     for (0..6) {
                   7154:         $code .= int( rand(9) );
                   7155:     }
                   7156:     return $code;
                   7157: }
                   7158: 
1.765     albertel 7159: # -------------------------------------------------- portfolio access checking
                   7160: 
                   7161: sub portfolio_access {
1.1172.2.77  raeburn  7162:     my ($requrl,$clientip) = @_;
1.765     albertel 7163:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7164:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7165:     if ($result) {
                   7166:         my %setters;
                   7167:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7168:             my ($startblock,$endblock) =
                   7169:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7170:             if ($startblock && $endblock) {
                   7171:                 return 'B';
                   7172:             }
                   7173:         } else {
                   7174:             my ($startblock,$endblock) =
                   7175:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7176:             if ($startblock && $endblock) {
                   7177:                 return 'B';
                   7178:             }
                   7179:         }
                   7180:     }
1.765     albertel 7181:     if ($result eq 'ok') {
1.766     albertel 7182:        return 'F';
1.765     albertel 7183:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7184:        return 'A';
1.765     albertel 7185:     }
1.766     albertel 7186:     return '';
1.765     albertel 7187: }
                   7188: 
                   7189: sub get_portfolio_access {
1.1172.2.77  raeburn  7190:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7191: 
                   7192:     if (!ref($access_hash)) {
                   7193: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7194: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7195: 						   $file_name);
                   7196: 	$access_hash = $access_controls{$file_name};
                   7197:     }
                   7198: 
1.1172.2.77  raeburn  7199:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7200:     my $now = time;
                   7201:     if (ref($access_hash) eq 'HASH') {
                   7202:         foreach my $key (keys(%{$access_hash})) {
                   7203:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7204:             if ($start > $now) {
                   7205:                 next;
                   7206:             }
                   7207:             if ($end && $end<$now) {
                   7208:                 next;
                   7209:             }
                   7210:             if ($scope eq 'public') {
                   7211:                 $public = $key;
                   7212:                 last;
                   7213:             } elsif ($scope eq 'guest') {
                   7214:                 $guest = $key;
                   7215:             } elsif ($scope eq 'domains') {
                   7216:                 push(@domains,$key);
                   7217:             } elsif ($scope eq 'users') {
                   7218:                 push(@users,$key);
                   7219:             } elsif ($scope eq 'course') {
                   7220:                 push(@courses,$key);
                   7221:             } elsif ($scope eq 'group') {
                   7222:                 push(@groups,$key);
1.1172.2.77  raeburn  7223:             } elsif ($scope eq 'ip') {
                   7224:                 push(@ips,$key);
1.765     albertel 7225:             }
                   7226:         }
                   7227:         if ($public) {
                   7228:             return 'ok';
1.1172.2.77  raeburn  7229:         } elsif (@ips > 0) {
                   7230:             my $allowed;
                   7231:             foreach my $ipkey (@ips) {
                   7232:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7233:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7234:                         $allowed = 1;
                   7235:                         last;
                   7236:                     }
                   7237:                 }
                   7238:             }
                   7239:             if ($allowed) {
                   7240:                 return 'ok';
                   7241:             }
1.765     albertel 7242:         }
                   7243:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7244:             if ($guest) {
                   7245:                 return $guest;
                   7246:             }
                   7247:         } else {
                   7248:             if (@domains > 0) {
                   7249:                 foreach my $domkey (@domains) {
                   7250:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7251:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7252:                             return 'ok';
                   7253:                         }
                   7254:                     }
                   7255:                 }
                   7256:             }
                   7257:             if (@users > 0) {
                   7258:                 foreach my $userkey (@users) {
1.865     raeburn  7259:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7260:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7261:                             if (ref($item) eq 'HASH') {
                   7262:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7263:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7264:                                     return 'ok';
                   7265:                                 }
                   7266:                             }
                   7267:                         }
                   7268:                     } 
1.765     albertel 7269:                 }
                   7270:             }
                   7271:             my %roleshash;
                   7272:             my @courses_and_groups = @courses;
                   7273:             push(@courses_and_groups,@groups); 
                   7274:             if (@courses_and_groups > 0) {
                   7275:                 my (%allgroups,%allroles); 
                   7276:                 my ($start,$end,$role,$sec,$group);
                   7277:                 foreach my $envkey (%env) {
1.1060    raeburn  7278:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7279:                         my $cid = $2.'_'.$3; 
                   7280:                         if ($1 eq 'gr') {
                   7281:                             $group = $4;
                   7282:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7283:                         } else {
                   7284:                             if ($4 eq '') {
                   7285:                                 $sec = 'none';
                   7286:                             } else {
                   7287:                                 $sec = $4;
                   7288:                             }
                   7289:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7290:                         }
1.811     albertel 7291:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7292:                         my $cid = $2.'_'.$3;
                   7293:                         if ($4 eq '') {
                   7294:                             $sec = 'none';
                   7295:                         } else {
                   7296:                             $sec = $4;
                   7297:                         }
                   7298:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7299:                     }
                   7300:                 }
                   7301:                 if (keys(%allroles) == 0) {
                   7302:                     return;
                   7303:                 }
                   7304:                 foreach my $key (@courses_and_groups) {
                   7305:                     my %content = %{$$access_hash{$key}};
                   7306:                     my $cnum = $content{'number'};
                   7307:                     my $cdom = $content{'domain'};
                   7308:                     my $cid = $cdom.'_'.$cnum;
                   7309:                     if (!exists($allroles{$cid})) {
                   7310:                         next;
                   7311:                     }    
                   7312:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7313:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7314:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7315:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7316:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7317:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7318:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7319:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7320:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7321:                                         if (grep/^all$/,@sections) {
                   7322:                                             return 'ok';
                   7323:                                         } else {
                   7324:                                             if (grep/^$sec$/,@sections) {
                   7325:                                                 return 'ok';
                   7326:                                             }
                   7327:                                         }
                   7328:                                     }
                   7329:                                 }
                   7330:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7331:                                     if (grep/^none$/,@groups) {
                   7332:                                         return 'ok';
                   7333:                                     }
                   7334:                                 } else {
                   7335:                                     if (grep/^all$/,@groups) {
                   7336:                                         return 'ok';
                   7337:                                     } 
                   7338:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7339:                                         if (grep/^$group$/,@groups) {
                   7340:                                             return 'ok';
                   7341:                                         }
                   7342:                                     }
                   7343:                                 } 
                   7344:                             }
                   7345:                         }
                   7346:                     }
                   7347:                 }
                   7348:             }
                   7349:             if ($guest) {
                   7350:                 return $guest;
                   7351:             }
                   7352:         }
                   7353:     }
                   7354:     return;
                   7355: }
                   7356: 
                   7357: sub course_group_datechecker {
                   7358:     my ($dates,$now,$status) = @_;
                   7359:     my ($start,$end) = split(/\./,$dates);
                   7360:     if (!$start && !$end) {
                   7361:         return 'ok';
                   7362:     }
                   7363:     if (grep/^active$/,@{$status}) {
                   7364:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7365:             return 'ok';
                   7366:         }
                   7367:     }
                   7368:     if (grep/^previous$/,@{$status}) {
                   7369:         if ($end > $now ) {
                   7370:             return 'ok';
                   7371:         }
                   7372:     }
                   7373:     if (grep/^future$/,@{$status}) {
                   7374:         if ($start > $now) {
                   7375:             return 'ok';
                   7376:         }
                   7377:     }
                   7378:     return; 
                   7379: }
                   7380: 
                   7381: sub parse_portfolio_url {
                   7382:     my ($url) = @_;
                   7383: 
                   7384:     my ($type,$udom,$unum,$group,$file_name);
                   7385:     
1.823     albertel 7386:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7387: 	$type = 1;
                   7388:         $udom = $1;
                   7389:         $unum = $2;
                   7390:         $file_name = $3;
1.823     albertel 7391:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7392: 	$type = 2;
                   7393:         $udom = $1;
                   7394:         $unum = $2;
                   7395:         $group = $3;
                   7396:         $file_name = $3.'/'.$4;
                   7397:     }
                   7398:     if (wantarray) {
                   7399: 	return ($type,$udom,$unum,$file_name,$group);
                   7400:     }
                   7401:     return $type;
                   7402: }
                   7403: 
                   7404: sub is_portfolio_url {
                   7405:     my ($url) = @_;
                   7406:     return scalar(&parse_portfolio_url($url));
                   7407: }
                   7408: 
1.798     raeburn  7409: sub is_portfolio_file {
                   7410:     my ($file) = @_;
1.820     raeburn  7411:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7412:         return 1;
                   7413:     }
                   7414:     return;
                   7415: }
                   7416: 
1.976     raeburn  7417: sub usertools_access {
1.1084    raeburn  7418:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7419:     my ($access,%tools);
                   7420:     if ($context eq '') {
                   7421:         $context = 'tools';
                   7422:     }
                   7423:     if ($context eq 'requestcourses') {
                   7424:         %tools = (
                   7425:                       official   => 1,
                   7426:                       unofficial => 1,
1.1006    raeburn  7427:                       community  => 1,
1.1172.2.37  raeburn  7428:                       textbook   => 1,
1.985     raeburn  7429:                  );
1.1172.2.9  raeburn  7430:     } elsif ($context eq 'requestauthor') {
                   7431:         %tools = (
                   7432:                       requestauthor => 1,
                   7433:                  );
1.985     raeburn  7434:     } else {
                   7435:         %tools = (
                   7436:                       aboutme   => 1,
                   7437:                       blog      => 1,
1.1172.2.6  raeburn  7438:                       webdav    => 1,
1.985     raeburn  7439:                       portfolio => 1,
                   7440:                  );
                   7441:     }
1.976     raeburn  7442:     return if (!defined($tools{$tool}));
                   7443: 
1.1172.2.35  raeburn  7444:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7445:         $udom = $env{'user.domain'};
                   7446:         $uname = $env{'user.name'};
                   7447:     }
                   7448: 
1.978     raeburn  7449:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7450:         if ($action ne 'reload') {
1.985     raeburn  7451:             if ($context eq 'requestcourses') {
                   7452:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7453:             } elsif ($context eq 'requestauthor') {
                   7454:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7455:             } else {
                   7456:                 return $env{'environment.availabletools.'.$tool};
                   7457:             }
                   7458:         }
1.976     raeburn  7459:     }
                   7460: 
1.1172.2.9  raeburn  7461:     my ($toolstatus,$inststatus,$envkey);
                   7462:     if ($context eq 'requestauthor') {
                   7463:         $envkey = $context;
                   7464:     } else {
                   7465:         $envkey = $context.'.'.$tool;
                   7466:     }
1.976     raeburn  7467: 
1.985     raeburn  7468:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7469:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7470:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7471:         $inststatus = $env{'environment.inststatus'};
                   7472:     } else {
1.1084    raeburn  7473:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7474:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7475:             $inststatus = $userenvref->{'inststatus'};
                   7476:         } else {
1.1172.2.9  raeburn  7477:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7478:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7479:             $inststatus = $userenv{'inststatus'};
                   7480:         }
1.976     raeburn  7481:     }
                   7482: 
                   7483:     if ($toolstatus ne '') {
                   7484:         if ($toolstatus) {
                   7485:             $access = 1;
                   7486:         } else {
                   7487:             $access = 0;
                   7488:         }
                   7489:         return $access;
                   7490:     }
                   7491: 
1.1084    raeburn  7492:     my ($is_adv,%domdef);
                   7493:     if (ref($is_advref) eq 'HASH') {
                   7494:         $is_adv = $is_advref->{'is_adv'};
                   7495:     } else {
                   7496:         $is_adv = &is_advanced_user($udom,$uname);
                   7497:     }
                   7498:     if (ref($domdefref) eq 'HASH') {
                   7499:         %domdef = %{$domdefref};
                   7500:     } else {
                   7501:         %domdef = &get_domain_defaults($udom);
                   7502:     }
1.976     raeburn  7503:     if (ref($domdef{$tool}) eq 'HASH') {
                   7504:         if ($is_adv) {
                   7505:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7506:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7507:                     $access = 1;
                   7508:                 } else {
                   7509:                     $access = 0;
                   7510:                 }
                   7511:                 return $access;
                   7512:             }
                   7513:         }
                   7514:         if ($inststatus ne '') {
                   7515:             my ($hasaccess,$hasnoaccess);
                   7516:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7517:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7518:                     if ($domdef{$tool}{$affiliation}) {
                   7519:                         $hasaccess = 1;
                   7520:                     } else {
                   7521:                         $hasnoaccess = 1;
                   7522:                     }
                   7523:                 }
                   7524:             }
                   7525:             if ($hasaccess || $hasnoaccess) {
                   7526:                 if ($hasaccess) {
                   7527:                     $access = 1;
                   7528:                 } elsif ($hasnoaccess) {
                   7529:                     $access = 0; 
                   7530:                 }
                   7531:                 return $access;
                   7532:             }
                   7533:         } else {
                   7534:             if ($domdef{$tool}{'default'} ne '') {
                   7535:                 if ($domdef{$tool}{'default'}) {
                   7536:                     $access = 1;
                   7537:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7538:                     $access = 0;
                   7539:                 }
                   7540:                 return $access;
                   7541:             }
                   7542:         }
                   7543:     } else {
1.1172.2.6  raeburn  7544:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7545:             $access = 1;
                   7546:         } else {
                   7547:             $access = 0;
                   7548:         }
1.976     raeburn  7549:         return $access;
                   7550:     }
                   7551: }
                   7552: 
1.1050    raeburn  7553: sub is_course_owner {
                   7554:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7555:     if (($udom eq '') || ($uname eq '')) {
                   7556:         $udom = $env{'user.domain'};
                   7557:         $uname = $env{'user.name'};
                   7558:     }
                   7559:     unless (($udom eq '') || ($uname eq '')) {
                   7560:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7561:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7562:                 return 1;
                   7563:             } else {
                   7564:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7565:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7566:                     return 1;
                   7567:                 }
                   7568:             }
                   7569:         }
                   7570:     }
                   7571:     return;
                   7572: }
                   7573: 
1.976     raeburn  7574: sub is_advanced_user {
                   7575:     my ($udom,$uname) = @_;
1.1085    raeburn  7576:     if ($udom ne '' && $uname ne '') {
                   7577:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7578:             if (wantarray) {
                   7579:                 return ($env{'user.adv'},$env{'user.author'});
                   7580:             } else {
                   7581:                 return $env{'user.adv'};
                   7582:             }
1.1085    raeburn  7583:         }
                   7584:     }
1.976     raeburn  7585:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7586:     my %allroles;
1.1128    raeburn  7587:     my ($is_adv,$is_author);
1.976     raeburn  7588:     foreach my $role (keys(%roleshash)) {
                   7589:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7590:         my $area = '/'.$tdomain.'/'.$trest;
                   7591:         if ($sec ne '') {
                   7592:             $area .= '/'.$sec;
                   7593:         }
                   7594:         if (($area ne '') && ($trole ne '')) {
                   7595:             my $spec=$trole.'.'.$area;
                   7596:             if ($trole =~ /^cr\//) {
                   7597:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7598:             } elsif ($trole ne 'gr') {
                   7599:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7600:             }
1.1128    raeburn  7601:             if ($trole eq 'au') {
                   7602:                 $is_author = 1;
                   7603:             }
1.976     raeburn  7604:         }
                   7605:     }
                   7606:     foreach my $role (keys(%allroles)) {
                   7607:         last if ($is_adv);
                   7608:         foreach my $item (split(/:/,$allroles{$role})) {
                   7609:             if ($item ne '') {
                   7610:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7611:                 if ($privilege eq 'adv') {
                   7612:                     $is_adv = 1;
                   7613:                     last;
                   7614:                 }
                   7615:             }
                   7616:         }
                   7617:     }
1.1128    raeburn  7618:     if (wantarray) {
                   7619:         return ($is_adv,$is_author);
                   7620:     }
1.976     raeburn  7621:     return $is_adv;
                   7622: }
1.798     raeburn  7623: 
1.1035    raeburn  7624: sub check_can_request {
1.1036    raeburn  7625:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7626:     my $canreq = 0;
                   7627:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7628:     my @options = ('approval','validate','autolimit');
                   7629:     my $optregex = join('|',@options);
                   7630:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7631:         foreach my $type (@{$types}) {
                   7632:             if (&usertools_access($env{'user.name'},
                   7633:                                   $env{'user.domain'},
                   7634:                                   $type,undef,'requestcourses')) {
                   7635:                 $canreq ++;
1.1036    raeburn  7636:                 if (ref($request_domains) eq 'HASH') {
                   7637:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7638:                 }
1.1035    raeburn  7639:                 if ($dom eq $env{'user.domain'}) {
                   7640:                     $can_request->{$type} = 1;
                   7641:                 }
                   7642:             }
                   7643:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7644:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7645:                 if (@curr > 0) {
1.1036    raeburn  7646:                     foreach my $item (@curr) {
                   7647:                         if (ref($request_domains) eq 'HASH') {
                   7648:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7649:                             if ($otherdom ne '') {
                   7650:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7651:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7652:                                         push(@{$request_domains->{$type}},$otherdom);
                   7653:                                     }
                   7654:                                 } else {
                   7655:                                     push(@{$request_domains->{$type}},$otherdom);
                   7656:                                 }
                   7657:                             }
                   7658:                         }
                   7659:                     }
                   7660:                     unless($dom eq $env{'user.domain'}) {
                   7661:                         $canreq ++;
1.1035    raeburn  7662:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7663:                             $can_request->{$type} = 1;
                   7664:                         }
                   7665:                     }
                   7666:                 }
                   7667:             }
                   7668:         }
                   7669:     }
                   7670:     return $canreq;
                   7671: }
                   7672: 
1.341     www      7673: # ---------------------------------------------- Custom access rule evaluation
                   7674: 
                   7675: sub customaccess {
                   7676:     my ($priv,$uri)=@_;
1.807     albertel 7677:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7678:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7679:     $udom = &LONCAPA::clean_domain($udom);
                   7680:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7681:     my $access=0;
1.800     albertel 7682:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7683: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7684: 	if ($type eq 'user') {
                   7685: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7686: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7687: 		if ($tdom) {
                   7688: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7689: 		}
1.896     albertel 7690: 		if ($tuname) {
                   7691: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7692: 		}
                   7693: 		$access=($effect eq 'allow');
                   7694: 		last;
                   7695: 	    }
                   7696: 	} else {
                   7697: 	    if ($role) {
                   7698: 		if ($role ne $urole) { next; }
                   7699: 	    }
                   7700: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7701: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7702: 		if ($tdom) {
                   7703: 		    if ($tdom ne $udom) { next; }
                   7704: 		}
                   7705: 		if ($tcrs) {
                   7706: 		    if ($tcrs ne $ucrs) { next; }
                   7707: 		}
                   7708: 		if ($tsec) {
                   7709: 		    if ($tsec ne $usec) { next; }
                   7710: 		}
                   7711: 		$access=($effect eq 'allow');
                   7712: 		last;
                   7713: 	    }
                   7714: 	    if ($realm eq '' && $role eq '') {
                   7715: 		$access=($effect eq 'allow');
                   7716: 	    }
1.402     bowersj2 7717: 	}
1.341     www      7718:     }
                   7719:     return $access;
                   7720: }
                   7721: 
1.103     harris41 7722: # ------------------------------------------------- Check for a user privilege
1.12      www      7723: 
                   7724: sub allowed {
1.1172.2.65  raeburn  7725:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7726:     my $ver_orguri=$uri;
1.439     www      7727:     $uri=&deversion($uri);
1.152     www      7728:     my $orguri=$uri;
1.52      www      7729:     $uri=&declutter($uri);
1.809     raeburn  7730: 
1.810     raeburn  7731:     if ($priv eq 'evb') {
                   7732: # Evade communication block restrictions for specified role in a course
                   7733:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7734:             return $1;
                   7735:         } else {
                   7736:             return;
                   7737:         }
                   7738:     }
                   7739: 
1.620     albertel 7740:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7741: # Free bre access to adm and meta resources
1.775     albertel 7742:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7743: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7744: 	&& ($priv eq 'bre')) {
1.14      www      7745: 	return 'F';
1.159     www      7746:     }
                   7747: 
1.545     banghart 7748: # Free bre access to user's own portfolio contents
1.714     raeburn  7749:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7750:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7751: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7752:         my %setters;
                   7753:         my ($startblock,$endblock) = 
                   7754:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7755:         if ($startblock && $endblock) {
                   7756:             return 'B';
                   7757:         } else {
                   7758:             return 'F';
                   7759:         }
1.545     banghart 7760:     }
                   7761: 
1.762     raeburn  7762: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7763:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7764:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7765:         if (exists($env{'request.course.id'})) {
                   7766:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7767:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7768:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7769:                 my $courseprivid=$env{'request.course.id'};
                   7770:                 $courseprivid=~s/\_/\//;
                   7771:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7772:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7773:                     return $1; 
1.762     raeburn  7774:                 } else {
                   7775:                     if ($env{'request.course.sec'}) {
                   7776:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7777:                     }
                   7778:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7779:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7780:                         return $2;
                   7781:                     }
1.714     raeburn  7782:                 }
                   7783:             }
                   7784:         }
                   7785:     }
                   7786: 
1.159     www      7787: # Free bre to public access
                   7788: 
                   7789:     if ($priv eq 'bre') {
1.238     www      7790:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7791: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7792:            return 'F'; 
                   7793:         }
1.238     www      7794:         if ($copyright eq 'priv') {
                   7795:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7796: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7797: 		return '';
                   7798:             }
                   7799:         }
                   7800:         if ($copyright eq 'domain') {
                   7801:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7802: 	    unless (($env{'user.domain'} eq $1) ||
                   7803:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7804: 		return '';
                   7805:             }
1.262     matthew  7806:         }
1.620     albertel 7807:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7808:             # Library role, so allow browsing of resources in this domain.
                   7809:             return 'F';
1.238     www      7810:         }
1.341     www      7811:         if ($copyright eq 'custom') {
                   7812: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7813:         }
1.14      www      7814:     }
1.264     matthew  7815:     # Domain coordinator is trying to create a course
1.620     albertel 7816:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7817:         # uri is the requested domain in this case.
                   7818:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7819:         # a role of dc for the domain in question.
1.620     albertel 7820:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7821:     }
1.29      www      7822: 
1.52      www      7823:     my $thisallowed='';
                   7824:     my $statecond=0;
                   7825:     my $courseprivid='';
                   7826: 
1.1039    raeburn  7827:     my $ownaccess;
1.1043    raeburn  7828:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7829:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7830:         if ($uri eq '') {
                   7831:             $ownaccess = 1;
                   7832:         } else {
                   7833:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7834:                 my $udom = $env{'user.domain'};
                   7835:                 my $uname = $env{'user.name'};
                   7836:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7837:                     $ownaccess = 1;
1.1040    raeburn  7838:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7839:                     unless ($uri =~ m{\.\./}) {
                   7840:                         $ownaccess = 1;
                   7841:                     }
                   7842:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7843:                     my $now = time;
                   7844:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7845:                         my $adom = $1;
                   7846:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7847:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7848:                                 my ($start,$end) = split('.',$env{$key});
                   7849:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7850:                                     $ownaccess = 1;
                   7851:                                     last;
                   7852:                                 }
                   7853:                             }
                   7854:                         }
                   7855:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7856:                         my $adom = $1;
                   7857:                         my $aname = $2;
1.1042    raeburn  7858:                         foreach my $role ('ca','aa') { 
                   7859:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7860:                                 my ($start,$end) =
                   7861:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7862:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7863:                                     $ownaccess = 1;
                   7864:                                     last;
                   7865:                                 }
1.1039    raeburn  7866:                             }
                   7867:                         }
                   7868:                     }
                   7869:                 }
                   7870:             }
                   7871:         }
                   7872:     }
                   7873: 
1.52      www      7874: # Course
                   7875: 
1.620     albertel 7876:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7877:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7878:             $thisallowed.=$1;
                   7879:         }
1.52      www      7880:     }
1.29      www      7881: 
1.52      www      7882: # Domain
                   7883: 
1.620     albertel 7884:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7885:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7886:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7887:             $thisallowed.=$1;
                   7888:         }
1.12      www      7889:     }
1.52      www      7890: 
1.1141    raeburn  7891: # User who is not author or co-author might still be able to edit
                   7892: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7893:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7894:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7895:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7896:             $thisallowed.=$1;
                   7897:         }
                   7898:     }
                   7899: 
1.52      www      7900: # Course: uri itself is a course
1.66      www      7901:     my $courseuri=$uri;
                   7902:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7903:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7904: 
1.620     albertel 7905:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7906:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  7907:         if ($priv eq 'mip') {
                   7908:             my $rem = $1;
                   7909:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   7910:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   7911:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7912:                 if ($cdom ne '') {
                   7913:                     my %passwdconf = &get_passwdconf($cdom);
                   7914:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   7915:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   7916:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   7917:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   7918:                                 unless (@inststatuses) {
                   7919:                                     @inststatuses = ('default');
                   7920:                                 }
                   7921:                                 foreach my $status (@inststatuses) {
                   7922:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   7923:                                         $thisallowed.=$rem;
                   7924:                                     }
                   7925:                                 }
                   7926:                             }
                   7927:                         }
                   7928:                     }
                   7929:                 }
                   7930:             }
                   7931:         } else {
                   7932:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   7933:                 $thisallowed.=$1;
                   7934:             }
1.1039    raeburn  7935:         }
1.12      www      7936:     }
1.29      www      7937: 
1.665     albertel 7938: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7939: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7940:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7941: 	$thisallowed='';
1.671     raeburn  7942:         my ($match)=&is_on_map($uri);
                   7943:         if ($match) {
                   7944:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7945:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7946:                 my $value = $1;
                   7947:                 if ($noblockcheck) {
                   7948:                     $thisallowed.=$value;
1.1162    raeburn  7949:                 } else {
1.1172.2.65  raeburn  7950:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7951:                     if (@blockers > 0) {
                   7952:                         $thisallowed = 'B';
                   7953:                     } else {
                   7954:                         $thisallowed.=$value;
                   7955:                     }
1.1162    raeburn  7956:                 }
1.671     raeburn  7957:             }
                   7958:         } else {
1.705     albertel 7959:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7960:             if ($refuri) {
                   7961:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7962:                     $thisallowed='F';
1.671     raeburn  7963:                 } else {
                   7964:                     $refuri=&declutter($refuri);
                   7965:                     my ($match) = &is_on_map($refuri);
                   7966:                     if ($match) {
1.1172.2.65  raeburn  7967:                         if ($noblockcheck) {
1.1162    raeburn  7968:                             $thisallowed='F';
1.1172.2.65  raeburn  7969:                         } else {
                   7970:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7971:                             if (@blockers > 0) {
                   7972:                                 $thisallowed = 'B';
                   7973:                             } else {
                   7974:                                 $thisallowed='F';
                   7975:                             }
1.1162    raeburn  7976:                         }
1.671     raeburn  7977:                     }
1.669     raeburn  7978:                 }
1.671     raeburn  7979:             }
                   7980:         }
1.314     www      7981:     }
1.492     albertel 7982: 
1.766     albertel 7983:     if ($priv eq 'bre'
                   7984: 	&& $thisallowed ne 'F' 
                   7985: 	&& $thisallowed ne '2'
                   7986: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7987: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7988:     }
                   7989:     
1.52      www      7990: # Full access at system, domain or course-wide level? Exit.
1.29      www      7991:     if ($thisallowed=~/F/) {
                   7992: 	return 'F';
                   7993:     }
                   7994: 
1.52      www      7995: # If this is generating or modifying users, exit with special codes
1.29      www      7996: 
1.643     www      7997:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7998: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7999: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8000: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8001: 	    unless ($auname) { return $thisallowed; }
                   8002: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8003: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8004: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8005: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8006: 	}
1.52      www      8007: 	return $thisallowed;
                   8008:     }
                   8009: #
1.103     harris41 8010: # Gathered so far: system, domain and course wide privileges
1.52      www      8011: #
                   8012: # Course: See if uri or referer is an individual resource that is part of 
                   8013: # the course
                   8014: 
1.620     albertel 8015:     if ($env{'request.course.id'}) {
1.232     www      8016: 
1.1172.2.115  raeburn  8017: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8018: 
                   8019:         if ($priv eq 'mip') {
                   8020:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8021:                 return $thisallowed;
                   8022:             } else {
                   8023:                 return '';
                   8024:             }
                   8025:         }
                   8026: 
1.620     albertel 8027:        $courseprivid=$env{'request.course.id'};
                   8028:        if ($env{'request.course.sec'}) {
                   8029:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8030:        }
                   8031:        $courseprivid=~s/\_/\//;
                   8032:        my $checkreferer=1;
1.232     www      8033:        my ($match,$cond)=&is_on_map($uri);
                   8034:        if ($match) {
                   8035:            $statecond=$cond;
1.620     albertel 8036:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8037:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8038:                my $value = $1;
                   8039:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8040:                    if ($noblockcheck) {
1.1162    raeburn  8041:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8042:                    } else {
                   8043:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8044:                        if (@blockers > 0) {
                   8045:                            $thisallowed = 'B';
                   8046:                        } else {
                   8047:                            $thisallowed.=$value;
                   8048:                        }
1.1162    raeburn  8049:                    }
                   8050:                } else {
                   8051:                    $thisallowed.=$value;
                   8052:                }
1.52      www      8053:                $checkreferer=0;
                   8054:            }
1.29      www      8055:        }
1.83      www      8056:        
1.148     www      8057:        if ($checkreferer) {
1.620     albertel 8058: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8059:             unless ($refuri) {
1.800     albertel 8060:                 foreach my $key (keys(%env)) {
                   8061: 		    if ($key=~/^httpref\..*\*/) {
                   8062: 			my $pattern=$key;
1.156     www      8063:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8064:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8065:                         $pattern=~s/\//\\\//g;
1.152     www      8066:                         if ($orguri=~/$pattern/) {
1.800     albertel 8067: 			    $refuri=$env{$key};
1.148     www      8068:                         }
                   8069:                     }
1.191     harris41 8070:                 }
1.148     www      8071:             }
1.232     www      8072: 
1.148     www      8073:          if ($refuri) { 
1.152     www      8074: 	  $refuri=&declutter($refuri);
1.232     www      8075:           my ($match,$cond)=&is_on_map($refuri);
                   8076:             if ($match) {
                   8077:               my $refstatecond=$cond;
1.620     albertel 8078:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8079:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8080:                   my $value = $1;
                   8081:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8082:                       if ($noblockcheck) {
1.1162    raeburn  8083:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8084:                       } else {
                   8085:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8086:                           if (@blockers > 0) {
                   8087:                               $thisallowed = 'B';
                   8088:                           } else {
                   8089:                               $thisallowed.=$value;
                   8090:                           }
1.1162    raeburn  8091:                       }
                   8092:                   } else {
                   8093:                       $thisallowed.=$value;
                   8094:                   }
1.53      www      8095:                   $uri=$refuri;
                   8096:                   $statecond=$refstatecond;
1.52      www      8097:               }
                   8098:           }
1.148     www      8099:         }
1.29      www      8100:        }
1.52      www      8101:    }
1.29      www      8102: 
1.52      www      8103: #
1.103     harris41 8104: # Gathered now: all privileges that could apply, and condition number
1.52      www      8105: # 
                   8106: #
                   8107: # Full or no access?
                   8108: #
1.29      www      8109: 
1.52      www      8110:     if ($thisallowed=~/F/) {
                   8111: 	return 'F';
                   8112:     }
1.29      www      8113: 
1.52      www      8114:     unless ($thisallowed) {
                   8115:         return '';
                   8116:     }
1.29      www      8117: 
1.52      www      8118: # Restrictions exist, deal with them
                   8119: #
                   8120: #   C:according to course preferences
                   8121: #   R:according to resource settings
                   8122: #   L:unless locked
                   8123: #   X:according to user session state
                   8124: #
                   8125: 
                   8126: # Possibly locked functionality, check all courses
1.54      www      8127: # Locks might take effect only after 10 minutes cache expiration for other
                   8128: # courses, and 2 minutes for current course
1.52      www      8129: 
                   8130:     my $envkey;
                   8131:     if ($thisallowed=~/L/) {
1.1000    raeburn  8132:         foreach $envkey (keys(%env)) {
1.54      www      8133:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8134:                my $courseid=$2;
                   8135:                my $roleid=$1.'.'.$2;
1.92      www      8136:                $courseid=~s/^\///;
1.54      www      8137:                my $expiretime=600;
1.620     albertel 8138:                if ($env{'request.role'} eq $roleid) {
1.54      www      8139: 		  $expiretime=120;
                   8140:                }
                   8141: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8142:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8143:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8144: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8145:                }
1.620     albertel 8146:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8147:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8148: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8149:                        &log($env{'user.domain'},$env{'user.name'},
                   8150:                             $env{'user.home'},
1.57      www      8151:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8152:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8153:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8154: 		       return '';
                   8155:                    }
                   8156:                }
1.620     albertel 8157:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8158:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8159: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8160:                        &log($env{'user.domain'},$env{'user.name'},
                   8161:                             $env{'user.home'},
1.57      www      8162:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8163:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8164:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8165: 		       return '';
                   8166:                    }
                   8167:                }
                   8168: 	   }
1.29      www      8169:        }
1.52      www      8170:     }
                   8171:    
                   8172: #
                   8173: # Rest of the restrictions depend on selected course
                   8174: #
                   8175: 
1.620     albertel 8176:     unless ($env{'request.course.id'}) {
1.766     albertel 8177: 	if ($thisallowed eq 'A') {
                   8178: 	    return 'A';
1.814     raeburn  8179:         } elsif ($thisallowed eq 'B') {
                   8180:             return 'B';
1.766     albertel 8181: 	} else {
                   8182: 	    return '1';
                   8183: 	}
1.52      www      8184:     }
1.29      www      8185: 
1.52      www      8186: #
                   8187: # Now user is definitely in a course
                   8188: #
1.53      www      8189: 
                   8190: 
                   8191: # Course preferences
                   8192: 
                   8193:    if ($thisallowed=~/C/) {
1.620     albertel 8194:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8195:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8196:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8197: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8198: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8199: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8200: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8201: 			$env{'request.course.id'});
                   8202: 	   }
1.237     www      8203:            return '';
                   8204:        }
                   8205: 
1.620     albertel 8206:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8207: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8208: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8209: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8210: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8211: 			$env{'request.course.id'});
                   8212: 	   }
1.54      www      8213:            return '';
                   8214:        }
1.53      www      8215:    }
                   8216: 
                   8217: # Resource preferences
                   8218: 
                   8219:    if ($thisallowed=~/R/) {
1.620     albertel 8220:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8221:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8222: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8223: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8224: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8225: 	   }
                   8226: 	   return '';
1.54      www      8227:        }
1.53      www      8228:    }
1.30      www      8229: 
1.246     www      8230: # Restricted by state or randomout?
1.30      www      8231: 
1.52      www      8232:    if ($thisallowed=~/X/) {
1.620     albertel 8233:       if ($env{'acc.randomout'}) {
1.579     albertel 8234: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8235:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8236:             return ''; 
                   8237:          }
1.247     www      8238:       }
                   8239:       if (&condval($statecond)) {
1.52      www      8240: 	 return '2';
                   8241:       } else {
                   8242:          return '';
                   8243:       }
                   8244:    }
1.30      www      8245: 
1.766     albertel 8246:     if ($thisallowed eq 'A') {
                   8247: 	return 'A';
1.814     raeburn  8248:     } elsif ($thisallowed eq 'B') {
                   8249:         return 'B';
1.766     albertel 8250:     }
1.52      www      8251:    return 'F';
1.232     www      8252: }
1.1162    raeburn  8253: 
1.1172.2.13  raeburn  8254: # ------------------------------------------- Check construction space access
                   8255: 
                   8256: sub constructaccess {
                   8257:     my ($url,$setpriv)=@_;
                   8258: 
                   8259: # We do not allow editing of previous versions of files
                   8260:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8261: 
                   8262: # Get username and domain from URL
                   8263:     my ($ownername,$ownerdomain,$ownerhome);
                   8264: 
                   8265:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8266:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8267: 
                   8268: # The URL does not really point to any authorspace, forget it
                   8269:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8270: 
                   8271: # Now we need to see if the user has access to the authorspace of
                   8272: # $ownername at $ownerdomain
                   8273: 
                   8274:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8275: # Real author for this?
                   8276:        $ownerhome = $env{'user.home'};
                   8277:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8278:           return ($ownername,$ownerdomain,$ownerhome);
                   8279:        }
                   8280:     } else {
                   8281: # Co-author for this?
                   8282:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8283:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8284:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8285:             return ($ownername,$ownerdomain,$ownerhome);
                   8286:         }
                   8287:     }
                   8288: 
                   8289: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8290: # we might as well leave
                   8291:    unless ($setpriv) { return ''; }
                   8292: 
                   8293: # Backdoor access?
                   8294:     my $allowed=&allowed('eco',$ownerdomain);
                   8295: # Nope
                   8296:     unless ($allowed) { return ''; }
                   8297: # Looks like we may have access, but could be locked by the owner of the construction space
                   8298:     if ($allowed eq 'U') {
                   8299:         my %blocked=&get('environment',['domcoord.author'],
                   8300:                          $ownerdomain,$ownername);
                   8301: # Is blocked by owner
                   8302:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8303:     }
                   8304:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8305: # Grant temporary access
                   8306:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8307:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8308:         if (!$update) { $update = $then; }
                   8309:         my $refresh=$env{'user.refresh.time'};
                   8310:         if (!$refresh) { $refresh = $update; }
                   8311:         my $now = time;
                   8312:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8313:                            $now,'ca','constructaccess');
                   8314:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8315:         return($ownername,$ownerdomain,$ownerhome);
                   8316:     }
                   8317: # No business here
                   8318:     return '';
                   8319: }
                   8320: 
1.1172.2.66  raeburn  8321: # ----------------------------------------------------------- Content Blocking
                   8322: 
                   8323: {
                   8324: # Caches for faster Course Contents display where content blocking
                   8325: # is in operation (i.e., interval param set) for timed quiz.
                   8326: #
                   8327: # User for whom data are being temporarily cached.
                   8328: my $cacheduser='';
                   8329: # Cached blockers for this user (a hash of blocking items).
                   8330: my %cachedblockers=();
                   8331: # When the data were last cached.
                   8332: my $cachedlast='';
                   8333: 
                   8334: sub load_all_blockers {
                   8335:     my ($uname,$udom,$blocks)=@_;
                   8336:     if (($uname ne '') && ($udom ne '')) {
                   8337:         if (($cacheduser eq $uname.':'.$udom) &&
                   8338:             (abs($cachedlast-time)<5)) {
                   8339:             return;
                   8340:         }
                   8341:     }
                   8342:     $cachedlast=time;
                   8343:     $cacheduser=$uname.':'.$udom;
                   8344:     %cachedblockers = &get_commblock_resources($blocks);
                   8345: }
                   8346: 
1.1162    raeburn  8347: sub get_comm_blocks {
                   8348:     my ($cdom,$cnum) = @_;
                   8349:     if ($cdom eq '' || $cnum eq '') {
                   8350:         return unless ($env{'request.course.id'});
                   8351:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8352:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8353:     }
                   8354:     my %commblocks;
                   8355:     my $hashid=$cdom.'_'.$cnum;
                   8356:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8357:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8358:         %commblocks = %{$blocksref};
                   8359:     } else {
                   8360:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8361:         my $cachetime = 600;
                   8362:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8363:     }
                   8364:     return %commblocks;
                   8365: }
                   8366: 
1.1172.2.66  raeburn  8367: sub get_commblock_resources {
                   8368:     my ($blocks) = @_;
                   8369:     my %blockers = ();
                   8370:     return %blockers unless ($env{'request.course.id'});
                   8371:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8372:     my %commblocks;
                   8373:     if (ref($blocks) eq 'HASH') {
                   8374:         %commblocks = %{$blocks};
                   8375:     } else {
                   8376:         %commblocks = &get_comm_blocks();
                   8377:     }
1.1172.2.66  raeburn  8378:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8379:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8380:     return %blockers unless (ref($navmap));
                   8381:     my $now = time;
1.1162    raeburn  8382:     foreach my $block (keys(%commblocks)) {
                   8383:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8384:             my ($start,$end) = ($1,$2);
                   8385:             if ($start <= $now && $end >= $now) {
                   8386:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8387:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8388:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8389:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8390:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8391:                             }
                   8392:                         }
                   8393:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8394:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8395:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8396:                             }
                   8397:                         }
                   8398:                     }
                   8399:                 }
                   8400:             }
                   8401:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8402:             my $item = $1;
1.1163    raeburn  8403:             my @to_test;
1.1162    raeburn  8404:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8405:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8406:                     my @interval;
                   8407:                     my $type = 'map';
                   8408:                     if ($item eq 'course') {
                   8409:                         $type = 'course';
                   8410:                         @interval=&EXT("resource.0.interval");
                   8411:                     } else {
                   8412:                         if ($item =~ /___\d+___/) {
                   8413:                             $type = 'resource';
                   8414:                             @interval=&EXT("resource.0.interval",$item);
                   8415:                             if (ref($navmap)) {
                   8416:                                 my $res = $navmap->getBySymb($item);
                   8417:                                 push(@to_test,$res);
                   8418:                             }
1.1162    raeburn  8419:                         } else {
1.1172.2.66  raeburn  8420:                             my $mapsymb = &symbread($item,1);
                   8421:                             if ($mapsymb) {
                   8422:                                 if (ref($navmap)) {
                   8423:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8424:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8425:                                     foreach my $res (@to_test) {
                   8426:                                         my $symb = $res->symb();
                   8427:                                         next if ($symb eq $mapsymb);
                   8428:                                         if ($symb ne '') {
                   8429:                                             @interval=&EXT("resource.0.interval",$symb);
                   8430:                                             if ($interval[1] eq 'map') {
                   8431:                                                 last;
1.1162    raeburn  8432:                                             }
                   8433:                                         }
                   8434:                                     }
                   8435:                                 }
                   8436:                             }
                   8437:                         }
1.1172.2.66  raeburn  8438:                     }
                   8439:                     if ($interval[0] =~ /^\d+$/) {
                   8440:                         my $first_access;
                   8441:                         if ($type eq 'resource') {
                   8442:                             $first_access=&get_first_access($interval[1],$item);
                   8443:                         } elsif ($type eq 'map') {
                   8444:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8445:                         } else {
                   8446:                             $first_access=&get_first_access($interval[1]);
                   8447:                         }
                   8448:                         if ($first_access) {
                   8449:                             my $timesup = $first_access+$interval[0];
                   8450:                             if ($timesup > $now) {
                   8451:                                 my $activeblock;
                   8452:                                 foreach my $res (@to_test) {
                   8453:                                     if ($res->answerable()) {
                   8454:                                         $activeblock = 1;
                   8455:                                         last;
                   8456:                                     }
                   8457:                                 }
                   8458:                                 if ($activeblock) {
                   8459:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8460:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8461:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8462:                                          }
                   8463:                                     }
                   8464:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8465:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8466:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8467:                                         }
1.1162    raeburn  8468:                                     }
                   8469:                                 }
                   8470:                             }
                   8471:                         }
                   8472:                     }
                   8473:                 }
                   8474:             }
                   8475:         }
                   8476:     }
1.1172.2.66  raeburn  8477:     return %blockers;
1.1162    raeburn  8478: }
                   8479: 
1.1172.2.66  raeburn  8480: sub has_comm_blocking {
                   8481:     my ($priv,$symb,$uri,$blocks) = @_;
                   8482:     my @blockers;
                   8483:     return unless ($env{'request.course.id'});
                   8484:     return unless ($priv eq 'bre');
                   8485:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8486:     return if ($env{'request.state'} eq 'construct');
                   8487:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8488:     return unless (keys(%cachedblockers) > 0);
                   8489:     my (%possibles,@symbs);
                   8490:     if (!$symb) {
                   8491:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8492:     }
1.1172.2.66  raeburn  8493:     if ($symb) {
                   8494:         @symbs = ($symb);
                   8495:     } elsif (keys(%possibles)) {
                   8496:         @symbs = keys(%possibles);
                   8497:     }
                   8498:     my $noblock;
                   8499:     foreach my $symb (@symbs) {
                   8500:         last if ($noblock);
                   8501:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8502:         foreach my $block (keys(%cachedblockers)) {
                   8503:             if ($block =~ /^firstaccess____(.+)$/) {
                   8504:                 my $item = $1;
                   8505:                 if (($item eq $map) || ($item eq $symb)) {
                   8506:                     $noblock = 1;
                   8507:                     last;
                   8508:                 }
1.1162    raeburn  8509:             }
1.1172.2.66  raeburn  8510:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8511:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8512:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8513:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8514:                             push(@blockers,$block);
                   8515:                         }
                   8516:                     }
                   8517:                 }
                   8518:             }
                   8519:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8520:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8521:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8522:                         push(@blockers,$block);
                   8523:                     }
                   8524:                 }
1.1162    raeburn  8525:             }
                   8526:         }
                   8527:     }
1.1172.2.66  raeburn  8528:     return if ($noblock);
                   8529:     return @blockers;
                   8530: }
1.1162    raeburn  8531: }
                   8532: 
1.1172.2.66  raeburn  8533: # -------------------------------- Deversion and split uri into path an filename
                   8534: 
1.1133    foxr     8535: #
1.1172.2.66  raeburn  8536: #   Removes the version from a URI and
1.1133    foxr     8537: #   splits it in to its filename and path to the filename.
                   8538: #   Seems like File::Basename could have done this more clearly.
                   8539: #   Parameters:
                   8540: #      $uri   - input URI
                   8541: #   Returns:
                   8542: #     Two element list consisting of 
                   8543: #     $pathname  - the URI up to and excluding the trailing /
                   8544: #     $filename  - The part of the URI following the last /
                   8545: #  NOTE:
                   8546: #    Another realization of this is simply:
                   8547: #    use File::Basename;
                   8548: #    ...
                   8549: #    $uri = shift;
                   8550: #    $filename = basename($uri);
                   8551: #    $path     = dirname($uri);
                   8552: #    return ($filename, $path);
                   8553: #
                   8554: #     The implementation below is probably faster however.
                   8555: #
1.710     albertel 8556: sub split_uri_for_cond {
                   8557:     my $uri=&deversion(&declutter(shift));
                   8558:     my @uriparts=split(/\//,$uri);
                   8559:     my $filename=pop(@uriparts);
                   8560:     my $pathname=join('/',@uriparts);
                   8561:     return ($pathname,$filename);
                   8562: }
1.232     www      8563: # --------------------------------------------------- Is a resource on the map?
                   8564: 
                   8565: sub is_on_map {
1.710     albertel 8566:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8567:     #Trying to find the conditional for the file
1.620     albertel 8568:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8569: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8570:     if ($match) {
1.289     bowersj2 8571: 	return (1,$1);
                   8572:     } else {
1.434     www      8573: 	return (0,0);
1.289     bowersj2 8574:     }
1.12      www      8575: }
                   8576: 
1.427     www      8577: # --------------------------------------------------------- Get symb from alias
                   8578: 
                   8579: sub get_symb_from_alias {
                   8580:     my $symb=shift;
                   8581:     my ($map,$resid,$url)=&decode_symb($symb);
                   8582: # Already is a symb
                   8583:     if ($url) { return $symb; }
                   8584: # Must be an alias
                   8585:     my $aliassymb='';
                   8586:     my %bighash;
1.620     albertel 8587:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8588:                             &GDBM_READER(),0640)) {
                   8589:         my $rid=$bighash{'mapalias_'.$symb};
                   8590: 	if ($rid) {
                   8591: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8592: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8593: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8594: 	}
                   8595:         untie %bighash;
                   8596:     }
                   8597:     return $aliassymb;
                   8598: }
                   8599: 
1.12      www      8600: # ----------------------------------------------------------------- Define Role
                   8601: 
                   8602: sub definerole {
                   8603:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8604:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8605:     foreach my $role (split(':',$sysrole)) {
                   8606: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8607:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8608:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8609: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8610:                return "refused:s:$crole&$cqual"; 
                   8611:             }
                   8612:         }
1.191     harris41 8613:     }
1.800     albertel 8614:     foreach my $role (split(':',$domrole)) {
                   8615: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8616:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8617:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8618: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8619:                return "refused:d:$crole&$cqual"; 
                   8620:             }
                   8621:         }
1.191     harris41 8622:     }
1.800     albertel 8623:     foreach my $role (split(':',$courole)) {
                   8624: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8625:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8626:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8627: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8628:                return "refused:c:$crole&$cqual"; 
                   8629:             }
                   8630:         }
1.191     harris41 8631:     }
1.1172.2.84  raeburn  8632:     my $uhome;
                   8633:     if (($uname ne '') && ($udom ne '')) {
                   8634:         $uhome = &homeserver($uname,$udom);
                   8635:         return $uhome if ($uhome eq 'no_host');
                   8636:     } else {
                   8637:         $uname = $env{'user.name'};
                   8638:         $udom = $env{'user.domain'};
                   8639:         $uhome = $env{'user.home'};
                   8640:     }
1.620     albertel 8641:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8642:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8643:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8644:     return reply($command,$uhome);
1.12      www      8645:   } else {
                   8646:     return 'refused';
                   8647:   }
1.105     harris41 8648: }
                   8649: 
                   8650: # ---------------- Make a metadata query against the network of library servers
                   8651: 
                   8652: sub metadata_query {
1.1172.2.33  raeburn  8653:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8654:     my %rhash;
1.845     albertel 8655:     my %libserv = &all_library();
1.244     matthew  8656:     my @server_list = (defined($server_array) ? @$server_array
                   8657:                                               : keys(%libserv) );
                   8658:     for my $server (@server_list) {
1.1172.2.33  raeburn  8659:         my $domains = '';
                   8660:         if (ref($domains_hash) eq 'HASH') {
                   8661:             $domains = $domains_hash->{$server};    
                   8662:         }
1.118     harris41 8663: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8664: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8665: 	    $rhash{$server}=$reply;
                   8666: 	}
                   8667: 	else {
                   8668: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8669: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8670: 			     $server);
                   8671: 	    $rhash{$server}=$reply;
                   8672: 	}
1.112     harris41 8673:     }
1.118     harris41 8674:     return \%rhash;
1.240     www      8675: }
                   8676: 
                   8677: # ----------------------------------------- Send log queries and wait for reply
                   8678: 
                   8679: sub log_query {
                   8680:     my ($uname,$udom,$query,%filters)=@_;
                   8681:     my $uhome=&homeserver($uname,$udom);
                   8682:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8683:     my $uhost=&hostname($uhome);
1.800     albertel 8684:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8685:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8686:                        $uhome);
1.479     albertel 8687:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8688:     return get_query_reply($queryid);
                   8689: }
                   8690: 
1.818     raeburn  8691: # -------------------------- Update MySQL table for portfolio file
                   8692: 
                   8693: sub update_portfolio_table {
1.821     raeburn  8694:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8695:     if ($group ne '') {
                   8696:         $file_name =~s /^\Q$group\E//;
                   8697:     }
1.818     raeburn  8698:     my $homeserver = &homeserver($uname,$udom);
                   8699:     my $queryid=
1.821     raeburn  8700:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8701:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8702:     my $reply = &get_query_reply($queryid);
                   8703:     return $reply;
                   8704: }
                   8705: 
1.899     raeburn  8706: # -------------------------- Update MySQL allusers table
                   8707: 
                   8708: sub update_allusers_table {
                   8709:     my ($uname,$udom,$names) = @_;
                   8710:     my $homeserver = &homeserver($uname,$udom);
                   8711:     my $queryid=
                   8712:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8713:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8714:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8715:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8716:                'generation='.&escape($names->{'generation'}).'%%'.
                   8717:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8718:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8719:     return;
1.899     raeburn  8720: }
                   8721: 
1.508     raeburn  8722: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8723: 
                   8724: sub fetch_enrollment_query {
1.511     raeburn  8725:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8726:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8727:     my $maxtries = 1;
1.508     raeburn  8728:     if ($context eq 'automated') {
                   8729:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8730:         $sleep = 2;
                   8731:         $loopmax = 100;
1.547     raeburn  8732:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8733:     } else {
                   8734:         $homeserver = &homeserver($cnum,$dom);
                   8735:     }
1.838     albertel 8736:     my $host=&hostname($homeserver);
1.506     raeburn  8737:     my $cmd = '';
1.1000    raeburn  8738:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8739:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8740:     }
                   8741:     $cmd =~ s/%%$//;
                   8742:     $cmd = &escape($cmd);
                   8743:     my $query = 'fetchenrollment';
1.620     albertel 8744:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8745:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8746:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8747:         return 'error: '.$queryid;
                   8748:     }
1.1172.2.93  raeburn  8749:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8750:     my $tries = 1;
                   8751:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8752:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8753:         $tries ++;
                   8754:     }
1.526     raeburn  8755:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8756:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8757:     } else {
1.901     albertel 8758:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8759:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8760:             foreach my $line (@responses) {
                   8761:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8762:                 $$replyref{$key} = $value;
                   8763:             }
                   8764:         } else {
1.1117    foxr     8765:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8766:             foreach my $line (@responses) {
                   8767:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8768:                 $$replyref{$key} = $value;
                   8769:                 if ($value > 0) {
1.800     albertel 8770:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8771:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8772:                         my $destname = $pathname.'/'.$filename;
                   8773:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8774:                         if ($xml_classlist =~ /^error/) {
                   8775:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8776:                         } else {
1.1172.2.96  raeburn  8777:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8778:                                 print FILE &unescape($xml_classlist);
                   8779:                                 close(FILE);
1.526     raeburn  8780:                             } else {
                   8781:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8782:                             }
                   8783:                         }
                   8784:                     }
                   8785:                 }
                   8786:             }
                   8787:         }
                   8788:         return 'ok';
                   8789:     }
                   8790:     return 'error';
                   8791: }
                   8792: 
1.242     www      8793: sub get_query_reply {
1.1172.2.79  raeburn  8794:     my ($queryid,$sleep,$loopmax) = @_;
                   8795:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8796:         $sleep = 0.2;
                   8797:     }
                   8798:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8799:         $loopmax = 100;
                   8800:     }
1.1117    foxr     8801:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8802:     my $reply='';
1.1172.2.79  raeburn  8803:     for (1..$loopmax) {
                   8804: 	sleep($sleep);
1.240     www      8805:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8806: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8807: 		$reply = join('',<$fh>);
                   8808: 		close($fh);
1.240     www      8809: 	   } else { return 'error: reply_file_error'; }
1.242     www      8810:            return &unescape($reply);
                   8811: 	}
1.240     www      8812:     }
1.242     www      8813:     return 'timeout:'.$queryid;
1.240     www      8814: }
                   8815: 
                   8816: sub courselog_query {
1.241     www      8817: #
                   8818: # possible filters:
                   8819: # url: url or symb
                   8820: # username
                   8821: # domain
                   8822: # action: view, submit, grade
                   8823: # start: timestamp
                   8824: # end: timestamp
                   8825: #
1.240     www      8826:     my (%filters)=@_;
1.620     albertel 8827:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8828:     if ($filters{'url'}) {
                   8829: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8830:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8831:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8832:     }
1.620     albertel 8833:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8834:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8835:     return &log_query($cname,$cdom,'courselog',%filters);
                   8836: }
                   8837: 
                   8838: sub userlog_query {
1.858     raeburn  8839: #
                   8840: # possible filters:
                   8841: # action: log check role
                   8842: # start: timestamp
                   8843: # end: timestamp
                   8844: #
1.240     www      8845:     my ($uname,$udom,%filters)=@_;
                   8846:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8847: }
                   8848: 
1.506     raeburn  8849: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8850: 
                   8851: sub auto_run {
1.508     raeburn  8852:     my ($cnum,$cdom) = @_;
1.876     raeburn  8853:     my $response = 0;
                   8854:     my $settings;
                   8855:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8856:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8857:         $settings = $domconfig{'autoenroll'};
                   8858:         if ($settings->{'run'} eq '1') {
                   8859:             $response = 1;
                   8860:         }
                   8861:     } else {
1.934     raeburn  8862:         my $homeserver;
                   8863:         if (&is_course($cdom,$cnum)) {
                   8864:             $homeserver = &homeserver($cnum,$cdom);
                   8865:         } else {
                   8866:             $homeserver = &domain($cdom,'primary');
                   8867:         }
                   8868:         if ($homeserver ne 'no_host') {
                   8869:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8870:         }
1.876     raeburn  8871:     }
1.506     raeburn  8872:     return $response;
                   8873: }
1.776     albertel 8874: 
1.506     raeburn  8875: sub auto_get_sections {
1.508     raeburn  8876:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8877:     my $homeserver;
                   8878:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8879:         $homeserver = &homeserver($cnum,$cdom);
                   8880:     }
                   8881:     if (!defined($homeserver)) { 
                   8882:         if ($cdom =~ /^$match_domain$/) {
                   8883:             $homeserver = &domain($cdom,'primary');
                   8884:         }
                   8885:     }
                   8886:     my @secs;
                   8887:     if (defined($homeserver)) {
                   8888:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8889:         unless ($response eq 'refused') {
                   8890:             @secs = split(/:/,$response);
                   8891:         }
1.506     raeburn  8892:     }
                   8893:     return @secs;
                   8894: }
1.776     albertel 8895: 
1.506     raeburn  8896: sub auto_new_course {
1.1099    raeburn  8897:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8898:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8899:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8900:     return $response;
                   8901: }
1.776     albertel 8902: 
1.506     raeburn  8903: sub auto_validate_courseID {
1.508     raeburn  8904:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8905:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8906:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8907:     return $response;
                   8908: }
1.776     albertel 8909: 
1.1007    raeburn  8910: sub auto_validate_instcode {
1.1020    raeburn  8911:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8912:     my ($homeserver,$response);
                   8913:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8914:         $homeserver = &homeserver($cnum,$cdom);
                   8915:     }
                   8916:     if (!defined($homeserver)) {
                   8917:         if ($cdom =~ /^$match_domain$/) {
                   8918:             $homeserver = &domain($cdom,'primary');
                   8919:         }
                   8920:     }
1.1065    raeburn  8921:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8922:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8923:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8924:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8925: }
                   8926: 
1.506     raeburn  8927: sub auto_create_password {
1.873     raeburn  8928:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8929:     my ($homeserver,$response);
1.506     raeburn  8930:     my $create_passwd = 0;
                   8931:     my $authchk = '';
1.873     raeburn  8932:     if ($udom =~ /^$match_domain$/) {
                   8933:         $homeserver = &domain($udom,'primary');
                   8934:     }
                   8935:     if ($homeserver eq '') {
                   8936:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8937:             $homeserver = &homeserver($cnum,$cdom);
                   8938:         }
                   8939:     }
                   8940:     if ($homeserver eq '') {
                   8941:         $authchk = 'nodomain';
1.506     raeburn  8942:     } else {
1.873     raeburn  8943:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8944:         if ($response eq 'refused') {
                   8945:             $authchk = 'refused';
                   8946:         } else {
1.901     albertel 8947:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8948:         }
1.506     raeburn  8949:     }
                   8950:     return ($authparam,$create_passwd,$authchk);
                   8951: }
                   8952: 
1.706     raeburn  8953: sub auto_photo_permission {
                   8954:     my ($cnum,$cdom,$students) = @_;
                   8955:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8956:     my ($outcome,$perm_reqd,$conditions) = 
                   8957: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8958:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8959: 	return (undef,undef);
                   8960:     }
1.706     raeburn  8961:     return ($outcome,$perm_reqd,$conditions);
                   8962: }
                   8963: 
                   8964: sub auto_checkphotos {
                   8965:     my ($uname,$udom,$pid) = @_;
                   8966:     my $homeserver = &homeserver($uname,$udom);
                   8967:     my ($result,$resulttype);
                   8968:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8969: 				   &escape($uname).':'.&escape($pid),
                   8970: 				   $homeserver));
1.709     albertel 8971:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8972: 	return (undef,undef);
                   8973:     }
1.706     raeburn  8974:     if ($outcome) {
                   8975:         ($result,$resulttype) = split(/:/,$outcome);
                   8976:     } 
                   8977:     return ($result,$resulttype);
                   8978: }
                   8979: 
                   8980: sub auto_photochoice {
                   8981:     my ($cnum,$cdom) = @_;
                   8982:     my $homeserver = &homeserver($cnum,$cdom);
                   8983:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8984: 						       &escape($cdom),
                   8985: 						       $homeserver)));
1.709     albertel 8986:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8987: 	return (undef,undef);
                   8988:     }
1.706     raeburn  8989:     return ($update,$comment);
                   8990: }
                   8991: 
                   8992: sub auto_photoupdate {
                   8993:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8994:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8995:     my $host=&hostname($homeserver);
1.706     raeburn  8996:     my $cmd = '';
                   8997:     my $maxtries = 1;
1.800     albertel 8998:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8999:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9000:     }
                   9001:     $cmd =~ s/%%$//;
                   9002:     $cmd = &escape($cmd);
                   9003:     my $query = 'institutionalphotos';
                   9004:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9005:     unless ($queryid=~/^\Q$host\E\_/) {
                   9006:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9007:         return 'error: '.$queryid;
                   9008:     }
                   9009:     my $reply = &get_query_reply($queryid);
                   9010:     my $tries = 1;
                   9011:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9012:         $reply = &get_query_reply($queryid);
                   9013:         $tries ++;
                   9014:     }
                   9015:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9016:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9017:     } else {
                   9018:         my @responses = split(/:/,$reply);
                   9019:         my $outcome = shift(@responses); 
                   9020:         foreach my $item (@responses) {
                   9021:             my ($key,$value) = split(/=/,$item);
                   9022:             $$photo{$key} = $value;
                   9023:         }
                   9024:         return $outcome;
                   9025:     }
                   9026:     return 'error';
                   9027: }
                   9028: 
1.521     raeburn  9029: sub auto_instcode_format {
1.793     albertel 9030:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9031: 	$cat_order) = @_;
1.521     raeburn  9032:     my $courses = '';
1.772     raeburn  9033:     my @homeservers;
1.521     raeburn  9034:     if ($caller eq 'global') {
1.841     albertel 9035: 	my %servers = &get_servers($codedom,'library');
                   9036: 	foreach my $tryserver (keys(%servers)) {
                   9037: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9038: 		push(@homeservers,$tryserver);
                   9039: 	    }
1.584     raeburn  9040:         }
1.1022    raeburn  9041:     } elsif ($caller eq 'requests') {
                   9042:         if ($codedom =~ /^$match_domain$/) {
                   9043:             my $chome = &domain($codedom,'primary');
                   9044:             unless ($chome eq 'no_host') {
                   9045:                 push(@homeservers,$chome);
                   9046:             }
                   9047:         }
1.521     raeburn  9048:     } else {
1.772     raeburn  9049:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9050:     }
1.793     albertel 9051:     foreach my $code (keys(%{$instcodes})) {
                   9052:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9053:     }
                   9054:     chop($courses);
1.772     raeburn  9055:     my $ok_response = 0;
                   9056:     my $response;
                   9057:     while (@homeservers > 0 && $ok_response == 0) {
                   9058:         my $server = shift(@homeservers); 
                   9059:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9060:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9061:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9062: 		split(/:/,$response);
1.772     raeburn  9063:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9064:             push(@{$codetitles},&str2array($codetitles_str));
                   9065:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9066:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9067:             $ok_response = 1;
                   9068:         }
                   9069:     }
                   9070:     if ($ok_response) {
1.521     raeburn  9071:         return 'ok';
1.772     raeburn  9072:     } else {
                   9073:         return $response;
1.521     raeburn  9074:     }
                   9075: }
                   9076: 
1.792     raeburn  9077: sub auto_instcode_defaults {
                   9078:     my ($domain,$returnhash,$code_order) = @_;
                   9079:     my @homeservers;
1.841     albertel 9080: 
                   9081:     my %servers = &get_servers($domain,'library');
                   9082:     foreach my $tryserver (keys(%servers)) {
                   9083: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9084: 	    push(@homeservers,$tryserver);
                   9085: 	}
1.792     raeburn  9086:     }
1.841     albertel 9087: 
1.792     raeburn  9088:     my $response;
1.841     albertel 9089:     foreach my $server (@homeservers) {
1.792     raeburn  9090:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9091:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9092: 	
                   9093: 	foreach my $pair (split(/\&/,$response)) {
                   9094: 	    my ($name,$value)=split(/\=/,$pair);
                   9095: 	    if ($name eq 'code_order') {
                   9096: 		@{$code_order} = split(/\&/,&unescape($value));
                   9097: 	    } else {
                   9098: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9099: 	    }
                   9100: 	}
                   9101: 	return 'ok';
1.792     raeburn  9102:     }
1.841     albertel 9103: 
                   9104:     return $response;
1.1003    raeburn  9105: }
                   9106: 
                   9107: sub auto_possible_instcodes {
1.1007    raeburn  9108:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9109:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9110:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9111:         return;
                   9112:     }
1.1003    raeburn  9113:     my (@homeservers,$uhome);
                   9114:     if (defined(&domain($domain,'primary'))) {
                   9115:         $uhome=&domain($domain,'primary');
                   9116:         push(@homeservers,&domain($domain,'primary'));
                   9117:     } else {
                   9118:         my %servers = &get_servers($domain,'library');
                   9119:         foreach my $tryserver (keys(%servers)) {
                   9120:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9121:                 push(@homeservers,$tryserver);
                   9122:             }
                   9123:         }
                   9124:     }
                   9125:     my $response;
                   9126:     foreach my $server (@homeservers) {
                   9127:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9128:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9129:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9130:             split(':',$response);
                   9131:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9132:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9133:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9134:             my ($name,$value)=split('=',$item);
                   9135:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9136:         }
                   9137:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9138:             my ($name,$value)=split('=',$item);
                   9139:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9140:         }
                   9141:         return 'ok';
                   9142:     }
                   9143:     return $response;
                   9144: }
1.792     raeburn  9145: 
1.1010    raeburn  9146: sub auto_courserequest_checks {
                   9147:     my ($dom) = @_;
1.1020    raeburn  9148:     my ($homeserver,%validations);
                   9149:     if ($dom =~ /^$match_domain$/) {
                   9150:         $homeserver = &domain($dom,'primary');
                   9151:     }
                   9152:     unless ($homeserver eq 'no_host') {
                   9153:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9154:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9155:             my @items = split(/&/,$response);
                   9156:             foreach my $item (@items) {
                   9157:                 my ($key,$value) = split('=',$item);
                   9158:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9159:             }
                   9160:         }
                   9161:     }
1.1010    raeburn  9162:     return %validations; 
                   9163: }
                   9164: 
1.1020    raeburn  9165: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9166:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9167:     my ($homeserver,$response);
                   9168:     if ($dom =~ /^$match_domain$/) {
                   9169:         $homeserver = &domain($dom,'primary');
                   9170:     }
1.1172.2.43  raeburn  9171:     unless ($homeserver eq 'no_host') {
                   9172:         my $customdata;
                   9173:         if (ref($custominfo) eq 'HASH') {
                   9174:             $customdata = &freeze_escape($custominfo);
                   9175:         }
1.1020    raeburn  9176:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9177:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9178:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9179:                                     $customdata,$homeserver));
1.1020    raeburn  9180:     }
                   9181:     return $response;
                   9182: }
                   9183: 
1.777     albertel 9184: sub auto_validate_class_sec {
1.918     raeburn  9185:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9186:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9187:     my $ownerlist;
                   9188:     if (ref($owners) eq 'ARRAY') {
                   9189:         $ownerlist = join(',',@{$owners});
                   9190:     } else {
                   9191:         $ownerlist = $owners;
                   9192:     }
1.773     raeburn  9193:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9194:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9195:     return $response;
                   9196: }
                   9197: 
1.1172.2.94  raeburn  9198: sub auto_validate_instclasses {
                   9199:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9200:     my ($homeserver,%validations);
                   9201:     $homeserver = &homeserver($cnum,$cdom);
                   9202:     unless ($homeserver eq 'no_host') {
                   9203:         my $ownerlist;
                   9204:         if (ref($owners) eq 'ARRAY') {
                   9205:             $ownerlist = join(',',@{$owners});
                   9206:         } else {
                   9207:             $ownerlist = $owners;
                   9208:         }
                   9209:         if (ref($classesref) eq 'HASH') {
                   9210:             my $classes = &freeze_escape($classesref);
                   9211:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9212:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9213:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9214:                 my @items = split(/&/,$response);
                   9215:                 foreach my $item (@items) {
                   9216:                     my ($key,$value) = split('=',$item);
                   9217:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9218:                 }
                   9219:             }
                   9220:         }
                   9221:     }
                   9222:     return %validations;
                   9223: }
                   9224: 
1.1172.2.38  raeburn  9225: sub auto_crsreq_update {
                   9226:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9227:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9228:     my ($homeserver,%crsreqresponse);
                   9229:     if ($cdom =~ /^$match_domain$/) {
                   9230:         $homeserver = &domain($cdom,'primary');
                   9231:     }
                   9232:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9233:         my $info;
                   9234:         if (ref($inbound) eq 'HASH') {
                   9235:             $info = &freeze_escape($inbound);
                   9236:         }
                   9237:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9238:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9239:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9240:                             &escape($title).':'.&escape($code).':'.
                   9241:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9242:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9243:             my @items = split(/&/,$response);
                   9244:             foreach my $item (@items) {
                   9245:                 my ($key,$value) = split('=',$item);
                   9246:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9247:             }
                   9248:         }
                   9249:     }
                   9250:     return \%crsreqresponse;
                   9251: }
                   9252: 
1.1172.2.78  raeburn  9253: sub auto_export_grades {
                   9254:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9255:     my ($homeserver,%exportresponse);
                   9256:     if ($cdom =~ /^$match_domain$/) {
                   9257:         $homeserver = &domain($cdom,'primary');
                   9258:     }
                   9259:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9260:         my $info;
                   9261:         if (ref($inforef) eq 'HASH') {
                   9262:             $info = &freeze_escape($inforef);
                   9263:         }
                   9264:         if (ref($gradesref) eq 'HASH') {
                   9265:             my $grades = &freeze_escape($gradesref);
                   9266:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9267:                                 $info.':'.$grades,$homeserver);
                   9268:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9269:                 my @items = split(/&/,$response);
                   9270:                 foreach my $item (@items) {
                   9271:                     my ($key,$value) = split('=',$item);
                   9272:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9273:                 }
                   9274:             }
                   9275:         }
                   9276:     }
                   9277:     return \%exportresponse;
                   9278: }
                   9279: 
1.1172.2.68  raeburn  9280: sub check_instcode_cloning {
                   9281:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9282:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9283:         return;
                   9284:     }
                   9285:     my $canclone;
                   9286:     if (@{$code_order} > 0) {
                   9287:         my $instcoderegexp ='^';
                   9288:         my @clonecodes = split(/\&/,$cloner);
                   9289:         foreach my $item (@{$code_order}) {
                   9290:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9291:                 foreach my $pair (@clonecodes) {
                   9292:                     my ($key,$val) = split(/\=/,$pair,2);
                   9293:                     $val = &unescape($val);
                   9294:                     if ($key eq $item) {
                   9295:                         $instcoderegexp .= '('.$val.')';
                   9296:                         last;
                   9297:                     }
                   9298:                 }
                   9299:             } else {
                   9300:                 $instcoderegexp .= $codedefaults->{$item};
                   9301:             }
                   9302:         }
                   9303:         $instcoderegexp .= '$';
                   9304:         my (@from,@to);
                   9305:         eval {
                   9306:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9307:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9308:         };
                   9309:         if ((@from > 0) && (@to > 0)) {
                   9310:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9311:             if (!@diffs) {
                   9312:                 $canclone = 1;
                   9313:             }
                   9314:         }
                   9315:     }
                   9316:     return $canclone;
                   9317: }
                   9318: 
                   9319: sub default_instcode_cloning {
                   9320:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9321:     my (%codedefaults,@code_order,$canclone);
                   9322:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9323:         %codedefaults = %{$codedefaultsref};
                   9324:         @code_order = @{$codeorderref};
                   9325:     } elsif ($clonedom) {
                   9326:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9327:     }
                   9328:     if (($domdefclone) && (@code_order)) {
                   9329:         my @clonecodes = split(/\+/,$domdefclone);
                   9330:         my $instcoderegexp ='^';
                   9331:         foreach my $item (@code_order) {
                   9332:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9333:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9334:             } else {
                   9335:                 $instcoderegexp .= $codedefaults{$item};
                   9336:             }
                   9337:         }
                   9338:         $instcoderegexp .= '$';
                   9339:         my (@from,@to);
                   9340:         eval {
                   9341:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9342:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9343:         };
                   9344:         if ((@from > 0) && (@to > 0)) {
                   9345:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9346:             if (!@diffs) {
                   9347:                 $canclone = 1;
                   9348:             }
                   9349:         }
                   9350:     }
                   9351:     return $canclone;
                   9352: }
                   9353: 
1.679     raeburn  9354: # ------------------------------------------------------- Course Group routines
                   9355: 
                   9356: sub get_coursegroups {
1.809     raeburn  9357:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9358:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9359: }
                   9360: 
1.679     raeburn  9361: sub modify_coursegroup {
                   9362:     my ($cdom,$cnum,$groupsettings) = @_;
                   9363:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9364: }
                   9365: 
1.809     raeburn  9366: sub toggle_coursegroup_status {
                   9367:     my ($cdom,$cnum,$group,$action) = @_;
                   9368:     my ($from_namespace,$to_namespace);
                   9369:     if ($action eq 'delete') {
                   9370:         $from_namespace = 'coursegroups';
                   9371:         $to_namespace = 'deleted_groups';
                   9372:     } else {
                   9373:         $from_namespace = 'deleted_groups';
                   9374:         $to_namespace = 'coursegroups';
                   9375:     }
                   9376:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9377:     if (my $tmp = &error(%curr_group)) {
                   9378:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9379:         return ('read error',$tmp);
                   9380:     } else {
                   9381:         my %savedsettings = %curr_group; 
1.809     raeburn  9382:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9383:         my $deloutcome;
                   9384:         if ($result eq 'ok') {
1.809     raeburn  9385:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9386:         } else {
                   9387:             return ('write error',$result);
                   9388:         }
                   9389:         if ($deloutcome eq 'ok') {
                   9390:             return 'ok';
                   9391:         } else {
                   9392:             return ('delete error',$deloutcome);
                   9393:         }
                   9394:     }
                   9395: }
                   9396: 
1.679     raeburn  9397: sub modify_group_roles {
1.957     raeburn  9398:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9399:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9400:     my $role = 'gr/'.&escape($userprivs);
                   9401:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9402:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9403:     if ($result eq 'ok') {
                   9404:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9405:     }
1.679     raeburn  9406:     return $result;
                   9407: }
                   9408: 
                   9409: sub modify_coursegroup_membership {
                   9410:     my ($cdom,$cnum,$membership) = @_;
                   9411:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9412:     return $result;
                   9413: }
                   9414: 
1.682     raeburn  9415: sub get_active_groups {
                   9416:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9417:     my $now = time;
                   9418:     my %groups = ();
                   9419:     foreach my $key (keys(%env)) {
1.811     albertel 9420:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9421:             my ($start,$end) = split(/\./,$env{$key});
                   9422:             if (($end!=0) && ($end<$now)) { next; }
                   9423:             if (($start!=0) && ($start>$now)) { next; }
                   9424:             if ($1 eq $cdom && $2 eq $cnum) {
                   9425:                 $groups{$3} = $env{$key} ;
                   9426:             }
                   9427:         }
                   9428:     }
                   9429:     return %groups;
                   9430: }
                   9431: 
1.683     raeburn  9432: sub get_group_membership {
                   9433:     my ($cdom,$cnum,$group) = @_;
                   9434:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9435: }
                   9436: 
                   9437: sub get_users_groups {
                   9438:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9439:     my @usersgroups;
1.683     raeburn  9440:     my $cachetime=1800;
                   9441: 
                   9442:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9443:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9444:     if (defined($cached)) {
1.734     albertel 9445:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9446:     } else {  
                   9447:         $grouplist = '';
1.816     raeburn  9448:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9449:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9450:         my $access_end = $env{'course.'.$courseid.
                   9451:                               '.default_enrollment_end_date'};
                   9452:         my $now = time;
                   9453:         foreach my $key (keys(%roleshash)) {
                   9454:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9455:                 my $group = $1;
                   9456:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9457:                     my $start = $2;
                   9458:                     my $end = $1;
                   9459:                     if ($start == -1) { next; } # deleted from group
                   9460:                     if (($start!=0) && ($start>$now)) { next; }
                   9461:                     if (($end!=0) && ($end<$now)) {
                   9462:                         if ($access_end && $access_end < $now) {
                   9463:                             if ($access_end - $end < 86400) {
                   9464:                                 push(@usersgroups,$group);
1.733     raeburn  9465:                             }
                   9466:                         }
1.817     raeburn  9467:                         next;
1.733     raeburn  9468:                     }
1.817     raeburn  9469:                     push(@usersgroups,$group);
1.683     raeburn  9470:                 }
                   9471:             }
                   9472:         }
1.817     raeburn  9473:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9474:         $grouplist = join(':',@usersgroups);
                   9475:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9476:     }
1.733     raeburn  9477:     return @usersgroups;
1.683     raeburn  9478: }
                   9479: 
                   9480: sub devalidate_getgroups_cache {
                   9481:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9482:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9483: 
1.683     raeburn  9484:     my $hashid="$udom:$uname:$courseid";
                   9485:     &devalidate_cache_new('getgroups',$hashid);
                   9486: }
                   9487: 
1.12      www      9488: # ------------------------------------------------------------------ Plain Text
                   9489: 
                   9490: sub plaintext {
1.988     raeburn  9491:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9492:     if ($short =~ m{^cr/}) {
1.758     albertel 9493: 	return (split('/',$short))[-1];
                   9494:     }
1.742     raeburn  9495:     if (!defined($cid)) {
                   9496:         $cid = $env{'request.course.id'};
                   9497:     }
                   9498:     my %rolenames = (
1.1008    raeburn  9499:                       Course    => 'std',
                   9500:                       Community => 'alt1',
1.742     raeburn  9501:                     );
1.1037    raeburn  9502:     if ($cid ne '') {
                   9503:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9504:             unless ($forcedefault) {
                   9505:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9506:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9507:                 return &Apache::lonlocal::mt($roletext);
                   9508:             }
                   9509:         }
                   9510:     }
                   9511:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9512:         (defined($rolenames{$type})) && 
                   9513:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9514:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9515:     } elsif ($cid ne '') {
                   9516:         my $crstype = $env{'course.'.$cid.'.type'};
                   9517:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9518:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9519:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9520:         }
1.742     raeburn  9521:     }
1.1037    raeburn  9522:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9523: }
                   9524: 
                   9525: # ----------------------------------------------------------------- Assign Role
                   9526: 
                   9527: sub assignrole {
1.957     raeburn  9528:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9529:         $context)=@_;
1.21      www      9530:     my $mrole;
                   9531:     if ($role =~ /^cr\//) {
1.393     www      9532:         my $cwosec=$url;
1.811     albertel 9533:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9534: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9535:            my $refused = 1;
                   9536:            if ($context eq 'requestcourses') {
                   9537:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9538:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9539:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9540:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9541:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9542:                            if ($crsenv{'internal.courseowner'} eq
                   9543:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9544:                                $refused = '';
                   9545:                            }
                   9546:                        }
                   9547:                    }
                   9548:                }
                   9549:            }
                   9550:            if ($refused) {
                   9551:                &logthis('Refused custom assignrole: '.
                   9552:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9553:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9554:                return 'refused';
                   9555:            }
1.104     www      9556:         }
1.21      www      9557:         $mrole='cr';
1.678     raeburn  9558:     } elsif ($role =~ /^gr\//) {
                   9559:         my $cwogrp=$url;
1.811     albertel 9560:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9561:         unless (&allowed('mdg',$cwogrp)) {
                   9562:             &logthis('Refused group assignrole: '.
                   9563:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9564:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9565:             return 'refused';
                   9566:         }
                   9567:         $mrole='gr';
1.21      www      9568:     } else {
1.82      www      9569:         my $cwosec=$url;
1.811     albertel 9570:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9571:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9572:             my $refused;
                   9573:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9574:                 if (!(&allowed('c'.$role,$url))) {
                   9575:                     $refused = 1;
                   9576:                 }
                   9577:             } else {
                   9578:                 $refused = 1;
                   9579:             }
1.947     raeburn  9580:             if ($refused) {
1.1045    raeburn  9581:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9582:                 if (!$selfenroll && $context eq 'course') {
                   9583:                     my %crsenv;
                   9584:                     if ($role eq 'cc' || $role eq 'co') {
                   9585:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9586:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9587:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9588:                                 if ($crsenv{'internal.courseowner'} eq 
                   9589:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9590:                                     $refused = '';
                   9591:                                 }
                   9592:                             }
                   9593:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9594:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9595:                                 if ($crsenv{'internal.courseowner'} eq 
                   9596:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9597:                                     $refused = '';
                   9598:                                 }
                   9599:                             }
                   9600:                         }
                   9601:                     }
                   9602:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9603:                     $refused = '';
1.1017    raeburn  9604:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9605:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9606:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9607:                         my $wrongcc;
                   9608:                         if ($cnum =~ /^$match_community$/) {
                   9609:                             $wrongcc = 1 if ($role eq 'cc');
                   9610:                         } else {
                   9611:                             $wrongcc = 1 if ($role eq 'co');
                   9612:                         }
                   9613:                         unless ($wrongcc) {
                   9614:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9615:                             if ($crsenv{'internal.courseowner'} eq 
                   9616:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9617:                                 $refused = '';
                   9618:                             }
1.1017    raeburn  9619:                         }
                   9620:                     }
1.1172.2.9  raeburn  9621:                 } elsif ($context eq 'requestauthor') {
                   9622:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9623:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9624:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9625:                             $refused = '';
                   9626:                         } else {
                   9627:                             my %domdefaults = &get_domain_defaults($udom);
                   9628:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9629:                                 my $checkbystatus;
                   9630:                                 if ($env{'user.adv'}) {
                   9631:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9632:                                     if ($disposition eq 'automatic') {
                   9633:                                         $refused = '';
                   9634:                                     } elsif ($disposition eq '') {
                   9635:                                         $checkbystatus = 1;
                   9636:                                     }
                   9637:                                 } else {
                   9638:                                     $checkbystatus = 1;
                   9639:                                 }
                   9640:                                 if ($checkbystatus) {
                   9641:                                     if ($env{'environment.inststatus'}) {
                   9642:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9643:                                         foreach my $type (@inststatuses) {
                   9644:                                             if (($type ne '') &&
                   9645:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9646:                                                 $refused = '';
                   9647:                                             }
                   9648:                                         }
                   9649:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9650:                                         $refused = '';
                   9651:                                     }
                   9652:                                 }
                   9653:                             }
                   9654:                         }
                   9655:                     }
1.1017    raeburn  9656:                 }
                   9657:                 if ($refused) {
1.947     raeburn  9658:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9659:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9660: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9661:                     return 'refused';
                   9662:                 }
1.932     raeburn  9663:             }
1.1131    raeburn  9664:         } elsif ($role eq 'au') {
                   9665:             if ($url ne '/'.$udom.'/') {
                   9666:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9667:                          ' to assign author role for '.$uname.':'.$udom.
                   9668:                          ' in domain: '.$url.' refused (wrong domain).');
                   9669:                 return 'refused';
                   9670:             }
1.104     www      9671:         }
1.21      www      9672:         $mrole=$role;
                   9673:     }
1.620     albertel 9674:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9675:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9676:     if ($end) { $command.='_'.$end; }
1.21      www      9677:     if ($start) {
                   9678: 	if ($end) { 
1.81      www      9679:            $command.='_'.$start; 
1.21      www      9680:         } else {
1.81      www      9681:            $command.='_0_'.$start;
1.21      www      9682:         }
                   9683:     }
1.739     raeburn  9684:     my $origstart = $start;
                   9685:     my $origend = $end;
1.957     raeburn  9686:     my $delflag;
1.357     www      9687: # actually delete
                   9688:     if ($deleteflag) {
1.373     www      9689: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9690: # modify command to delete the role
1.620     albertel 9691:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9692:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9693: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9694: # set start and finish to negative values for userrolelog
                   9695:            $start=-1;
                   9696:            $end=-1;
1.957     raeburn  9697:            $delflag = 1;
1.357     www      9698:         }
                   9699:     }
                   9700: # send command
1.349     www      9701:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9702: # log new user role if status is ok
1.349     www      9703:     if ($answer eq 'ok') {
1.663     raeburn  9704: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9705:         if (($role eq 'cc') || ($role eq 'in') ||
                   9706:             ($role eq 'ep') || ($role eq 'ad') ||
                   9707:             ($role eq 'ta') || ($role eq 'st') ||
                   9708:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9709:             ($role eq 'co')) {
1.1172.2.13  raeburn  9710: # for course roles, perform group memberships changes triggered by role change.
                   9711:             unless ($role =~ /^gr/) {
                   9712:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9713:                                                  $origstart,$selfenroll,$context);
                   9714:             }
1.1172.2.9  raeburn  9715:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9716:                            $selfenroll,$context);
                   9717:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9718:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9719:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9720:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9721:                            $context);
                   9722:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9723:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9724:                              $context);
                   9725:         }
1.1053    raeburn  9726:         if ($role eq 'cc') {
                   9727:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9728:         }
1.349     www      9729:     }
                   9730:     return $answer;
1.169     harris41 9731: }
                   9732: 
1.1053    raeburn  9733: sub autoupdate_coowners {
                   9734:     my ($url,$end,$start,$uname,$udom) = @_;
                   9735:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9736:     if (($cdom ne '') && ($cnum ne '')) {
                   9737:         my $now = time;
                   9738:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9739:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9740:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9741:             my $instcode = $coursehash{'internal.coursecode'};
                   9742:             if ($instcode ne '') {
1.1056    raeburn  9743:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9744:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9745:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9746:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9747:                         if ($result eq 'valid') {
                   9748:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9749:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9750:                                     push(@newcoowners,$coowner);
                   9751:                                 }
                   9752:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9753:                                     push(@newcoowners,$uname.':'.$udom);
                   9754:                                 }
                   9755:                                 @newcoowners = sort(@newcoowners);
                   9756:                             } else {
                   9757:                                 push(@newcoowners,$uname.':'.$udom);
                   9758:                             }
                   9759:                         } else {
                   9760:                             if ($coursehash{'internal.co-owners'}) {
                   9761:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9762:                                     unless ($coowner eq $uname.':'.$udom) {
                   9763:                                         push(@newcoowners,$coowner);
                   9764:                                     }
                   9765:                                 }
                   9766:                                 unless (@newcoowners > 0) {
                   9767:                                     $delcoowners = 1;
                   9768:                                     $coowners = '';
                   9769:                                 }
                   9770:                             }
                   9771:                         }
                   9772:                         if (@newcoowners || $delcoowners) {
                   9773:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9774:                                             $delcoowners,@newcoowners);
                   9775:                         }
                   9776:                     }
                   9777:                 }
                   9778:             }
                   9779:         }
                   9780:     }
                   9781: }
                   9782: 
                   9783: sub store_coowners {
                   9784:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9785:     my $cid = $cdom.'_'.$cnum;
                   9786:     my ($coowners,$delresult,$putresult);
                   9787:     if (@newcoowners) {
                   9788:         $coowners = join(',',@newcoowners);
                   9789:         my %coownershash = (
                   9790:                             'internal.co-owners' => $coowners,
                   9791:                            );
                   9792:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9793:         if ($putresult eq 'ok') {
                   9794:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9795:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9796:             }
                   9797:         }
                   9798:     }
                   9799:     if ($delcoowners) {
                   9800:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9801:         if ($delresult eq 'ok') {
                   9802:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9803:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9804:             }
                   9805:         }
                   9806:     }
                   9807:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9808:         my %crsinfo =
                   9809:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9810:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9811:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9812:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9813:         }
                   9814:     }
                   9815: }
                   9816: 
1.169     harris41 9817: # -------------------------------------------------- Modify user authentication
1.197     www      9818: # Overrides without validation
                   9819: 
1.169     harris41 9820: sub modifyuserauth {
                   9821:     my ($udom,$uname,$umode,$upass)=@_;
                   9822:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9823:     my $allowed;
                   9824:     if (&allowed('mau',$udom)) {
                   9825:         $allowed = 1;
                   9826:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9827:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9828:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9829:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9830:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9831:         if (($cdom ne '') && ($cnum ne '')) {
                   9832:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9833:             if ($is_owner) {
                   9834:                 $allowed = 1;
                   9835:             }
                   9836:         }
                   9837:     }
                   9838:     unless ($allowed) { return 'refused'; }
1.197     www      9839:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9840:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9841:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9842:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9843: 		     &escape($upass),$uhome);
1.620     albertel 9844:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9845:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9846:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9847:     &log($udom,,$uname,$uhome,
1.620     albertel 9848:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9849:                                      $env{'user.name'}.', '.$umode.
1.197     www      9850:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9851:     unless ($reply eq 'ok') {
1.197     www      9852:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9853: 	return 'error: '.$reply;
                   9854:     }   
1.170     harris41 9855:     return 'ok';
1.80      www      9856: }
                   9857: 
1.81      www      9858: # --------------------------------------------------------------- Modify a user
1.80      www      9859: 
1.81      www      9860: sub modifyuser {
1.206     matthew  9861:     my ($udom,    $uname, $uid,
                   9862:         $umode,   $upass, $first,
                   9863:         $middle,  $last,  $gene,
1.1058    raeburn  9864:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9865:     $udom= &LONCAPA::clean_domain($udom);
                   9866:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9867:     my $showcandelete = 'none';
                   9868:     if (ref($candelete) eq 'ARRAY') {
                   9869:         if (@{$candelete} > 0) {
                   9870:             $showcandelete = join(', ',@{$candelete});
                   9871:         }
                   9872:     }
1.81      www      9873:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9874:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9875: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9876:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9877:                                      ' desiredhome not specified'). 
1.620     albertel 9878:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9879:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9880:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9881:     my $newuser;
                   9882:     if ($uhome eq 'no_host') {
                   9883:         $newuser = 1;
                   9884:     }
1.80      www      9885: # ----------------------------------------------------------------- Create User
1.406     albertel 9886:     if (($uhome eq 'no_host') && 
                   9887: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9888:         my $unhome='';
1.844     albertel 9889:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9890:             $unhome = $desiredhome;
1.620     albertel 9891: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9892: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9893:         } else { # load balancing routine for determining $unhome
1.81      www      9894:             my $loadm=10000000;
1.841     albertel 9895: 	    my %servers = &get_servers($udom,'library');
                   9896: 	    foreach my $tryserver (keys(%servers)) {
                   9897: 		my $answer=reply('load',$tryserver);
                   9898: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9899: 		    $loadm=$answer;
                   9900: 		    $unhome=$tryserver;
                   9901: 		}
1.80      www      9902: 	    }
                   9903:         }
                   9904:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9905: 	    return 'error: unable to find a home server for '.$uname.
                   9906:                    ' in domain '.$udom;
1.80      www      9907:         }
                   9908:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9909:                          &escape($upass),$unhome);
                   9910: 	unless ($reply eq 'ok') {
                   9911:             return 'error: '.$reply;
                   9912:         }   
1.230     stredwic 9913:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9914:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9915: 	    return 'error: unable verify users home machine.';
1.80      www      9916:         }
1.209     matthew  9917:     }   # End of creation of new user
1.80      www      9918: # ---------------------------------------------------------------------- Add ID
                   9919:     if ($uid) {
                   9920:        $uid=~tr/A-Z/a-z/;
                   9921:        my %uidhash=&idrget($udom,$uname);
1.196     www      9922:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9923:          && (!$forceid)) {
1.80      www      9924: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9925: 	      return 'error: user id "'.$uid.'" does not match '.
                   9926:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9927:           }
                   9928:        } else {
                   9929: 	  &idput($udom,($uname => $uid));
                   9930:        }
                   9931:     }
                   9932: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9933:     my @tmp=&get('environment',
1.899     raeburn  9934: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9935:                     'permanentemail','inststatus'],
1.134     albertel 9936: 		   $udom,$uname);
1.1075    raeburn  9937:     my (%names,%oldnames);
1.313     matthew  9938:     if ($tmp[0] =~ m/^error:.*/) { 
                   9939:         %names=(); 
                   9940:     } else {
                   9941:         %names = @tmp;
1.1075    raeburn  9942:         %oldnames = %names;
1.313     matthew  9943:     }
1.388     www      9944: #
1.1058    raeburn  9945: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9946: # of users did not contain them), do not overwrite existing values
                   9947: # unless field is in $candelete array ref.  
                   9948: #
                   9949: 
                   9950:     my @fields = ('firstname','middlename','lastname','generation',
                   9951:                   'permanentemail','id');
                   9952:     my %newvalues;
                   9953:     if (ref($candelete) eq 'ARRAY') {
                   9954:         foreach my $field (@fields) {
                   9955:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9956:                 if ($field eq 'firstname') {
                   9957:                     $names{$field} = $first;
                   9958:                 } elsif ($field eq 'middlename') {
                   9959:                     $names{$field} = $middle;
                   9960:                 } elsif ($field eq 'lastname') {
                   9961:                     $names{$field} = $last;
                   9962:                 } elsif ($field eq 'generation') { 
                   9963:                     $names{$field} = $gene;
                   9964:                 } elsif ($field eq 'permanentemail') {
                   9965:                     $names{$field} = $email;
                   9966:                 } elsif ($field eq 'id') {
                   9967:                     $names{$field}  = $uid;
                   9968:                 }
                   9969:             }
                   9970:         }
                   9971:     }
1.388     www      9972:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9973:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9974:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9975:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9976:     if ($email) {
                   9977:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9978:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9979:     }
1.899     raeburn  9980:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9981:     if (defined($inststatus)) {
                   9982:         $names{'inststatus'} = '';
                   9983:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9984:         if (ref($usertypes) eq 'HASH') {
                   9985:             my @okstatuses; 
                   9986:             foreach my $item (split(/:/,$inststatus)) {
                   9987:                 if (defined($usertypes->{$item})) {
                   9988:                     push(@okstatuses,$item);  
                   9989:                 }
                   9990:             }
                   9991:             if (@okstatuses) {
                   9992:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9993:             }
                   9994:         }
                   9995:     }
1.1075    raeburn  9996:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9997:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9998:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9999:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10000:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10001:     } else {
                   10002:         $logmsg .= ' during self creation';
                   10003:     }
1.1075    raeburn  10004:     my $changed;
                   10005:     if ($newuser) {
                   10006:         $changed = 1;
                   10007:     } else {
                   10008:         foreach my $field (@fields) {
                   10009:             if ($names{$field} ne $oldnames{$field}) {
                   10010:                 $changed = 1;
                   10011:                 last;
                   10012:             }
                   10013:         }
                   10014:     }
                   10015:     unless ($changed) {
                   10016:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10017:         &logthis($logmsg);
                   10018:         return 'ok';
                   10019:     }
                   10020:     my $reply = &put('environment', \%names, $udom,$uname);
                   10021:     if ($reply ne 'ok') { 
                   10022:         return 'error: '.$reply;
                   10023:     }
1.1087    raeburn  10024:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10025:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10026:     }
1.1075    raeburn  10027:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10028:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10029:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10030:     &logthis($logmsg);
1.134     albertel 10031:     return 'ok';
1.80      www      10032: }
                   10033: 
1.81      www      10034: # -------------------------------------------------------------- Modify student
1.80      www      10035: 
1.81      www      10036: sub modifystudent {
                   10037:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10038:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10039:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10040:     if (!$cid) {
1.620     albertel 10041: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10042: 	    return 'not_in_class';
                   10043: 	}
1.80      www      10044:     }
                   10045: # --------------------------------------------------------------- Make the user
1.81      www      10046:     my $reply=&modifyuser
1.209     matthew  10047: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10048:          $desiredhome,$email,$inststatus);
1.80      www      10049:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10050:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10051:     # student's environment
1.297     matthew  10052:     $uid = undef if (!$forceid);
1.455     albertel 10053:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10054: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10055:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10056:     return $reply;
                   10057: }
                   10058: 
                   10059: sub modify_student_enrollment {
1.1172.2.23  raeburn  10060:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10061:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10062:     my ($cdom,$cnum,$chome);
                   10063:     if (!$cid) {
1.620     albertel 10064: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10065: 	    return 'not_in_class';
                   10066: 	}
1.620     albertel 10067: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10068: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10069:     } else {
                   10070: 	($cdom,$cnum)=split(/_/,$cid);
                   10071:     }
1.620     albertel 10072:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10073:     if (!$chome) {
1.457     raeburn  10074: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10075:     }
1.455     albertel 10076:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10077:     # Make sure the user exists
1.81      www      10078:     my $uhome=&homeserver($uname,$udom);
                   10079:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10080: 	return 'error: no such user';
                   10081:     }
1.297     matthew  10082:     # Get student data if we were not given enough information
                   10083:     if (!defined($first)  || $first  eq '' || 
                   10084:         !defined($last)   || $last   eq '' || 
                   10085:         !defined($uid)    || $uid    eq '' || 
                   10086:         !defined($middle) || $middle eq '' || 
                   10087:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10088:         # They did not supply us with enough data to enroll the student, so
                   10089:         # we need to pick up more information.
1.297     matthew  10090:         my %tmp = &get('environment',
1.294     matthew  10091:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10092:                        ,$udom,$uname);
                   10093: 
1.800     albertel 10094:         #foreach my $key (keys(%tmp)) {
                   10095:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10096:         #}
1.294     matthew  10097:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10098:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10099:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10100:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10101:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10102:     }
1.556     albertel 10103:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10104:     my $user = "$uname:$udom";
                   10105:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10106:     my $reply=cput('classlist',
1.1148    raeburn  10107: 		   {$user => 
1.1172.2.76  raeburn  10108: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10109: 		   $cdom,$cnum);
1.1148    raeburn  10110:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10111:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10112:     } else { 
1.81      www      10113: 	return 'error: '.$reply;
                   10114:     }
1.297     matthew  10115:     # Add student role to user
1.83      www      10116:     my $uurl='/'.$cid;
1.81      www      10117:     $uurl=~s/\_/\//g;
                   10118:     if ($usec) {
                   10119: 	$uurl.='/'.$usec;
                   10120:     }
1.1148    raeburn  10121:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10122:                              $selfenroll,$context);
                   10123:     if ($result ne 'ok') {
                   10124:         if ($old_entry{$user} ne '') {
                   10125:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10126:         } else {
                   10127:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10128:         }
                   10129:     }
                   10130:     return $result; 
1.21      www      10131: }
                   10132: 
1.556     albertel 10133: sub format_name {
                   10134:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10135:     my $name;
                   10136:     if ($first ne 'lastname') {
                   10137: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10138:     } else {
                   10139: 	if ($lastname=~/\S/) {
                   10140: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10141: 	    $name=~s/\s+,/,/;
                   10142: 	} else {
                   10143: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10144: 	}
                   10145:     }
                   10146:     $name=~s/^\s+//;
                   10147:     $name=~s/\s+$//;
                   10148:     $name=~s/\s+/ /g;
                   10149:     return $name;
                   10150: }
                   10151: 
1.84      www      10152: # ------------------------------------------------- Write to course preferences
                   10153: 
                   10154: sub writecoursepref {
                   10155:     my ($courseid,%prefs)=@_;
                   10156:     $courseid=~s/^\///;
                   10157:     $courseid=~s/\_/\//g;
                   10158:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10159:     my $chome=homeserver($cnum,$cdomain);
                   10160:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10161: 	return 'error: no such course';
                   10162:     }
                   10163:     my $cstring='';
1.800     albertel 10164:     foreach my $pref (keys(%prefs)) {
                   10165: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10166:     }
1.84      www      10167:     $cstring=~s/\&$//;
                   10168:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10169: }
                   10170: 
                   10171: # ---------------------------------------------------------- Make/modify course
                   10172: 
                   10173: sub createcourse {
1.741     raeburn  10174:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10175:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10176:     $url=&declutter($url);
                   10177:     my $cid='';
1.1028    raeburn  10178:     if ($context eq 'requestcourses') {
                   10179:         my $can_create = 0;
                   10180:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10181:         if ($udom eq $ownerdom) {
                   10182:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10183:                                   $context)) {
                   10184:                 $can_create = 1;
                   10185:             }
                   10186:         } else {
                   10187:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10188:                                            $category);
                   10189:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10190:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10191:                 if (@curr > 0) {
                   10192:                     my @options = qw(approval validate autolimit);
                   10193:                     my $optregex = join('|',@options);
                   10194:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10195:                         $can_create = 1;
                   10196:                     }
                   10197:                 }
                   10198:             }
                   10199:         }
                   10200:         if ($can_create) {
                   10201:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10202:                 unless (&allowed('ccc',$udom)) {
                   10203:                     return 'refused'; 
                   10204:                 }
1.1017    raeburn  10205:             }
                   10206:         } else {
                   10207:             return 'refused';
                   10208:         }
1.1028    raeburn  10209:     } elsif (!&allowed('ccc',$udom)) {
                   10210:         return 'refused';
1.84      www      10211:     }
1.1011    raeburn  10212: # --------------------------------------------------------------- Get Unique ID
                   10213:     my $uname;
                   10214:     if ($cnum =~ /^$match_courseid$/) {
                   10215:         my $chome=&homeserver($cnum,$udom,'true');
                   10216:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10217:             $uname = $cnum;
                   10218:         } else {
1.1038    raeburn  10219:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10220:         }
                   10221:     } else {
1.1038    raeburn  10222:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10223:     }
                   10224:     return $uname if ($uname =~ /^error/);
                   10225: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10226:     if (!defined($course_server)) {
                   10227:         if (defined(&domain($udom,'primary'))) {
                   10228:             $course_server = &domain($udom,'primary');
                   10229:         } else {
                   10230:             $course_server = $env{'user.home'}; 
                   10231:         }
                   10232:     }
                   10233:     my %host_servers =
                   10234:         &Apache::lonnet::get_servers($udom,'library');
                   10235:     unless ($host_servers{$course_server}) {
                   10236:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10237:     }
1.84      www      10238: # ------------------------------------------------------------- Make the course
                   10239:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10240:                       $course_server);
1.84      www      10241:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10242:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10243:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10244: 	return 'error: no such course';
                   10245:     }
1.271     www      10246: # ----------------------------------------------------------------- Course made
1.516     raeburn  10247: # log existence
1.1029    raeburn  10248:     my $now = time;
1.918     raeburn  10249:     my $newcourse = {
                   10250:                     $udom.'_'.$uname => {
1.921     raeburn  10251:                                      description => $description,
                   10252:                                      inst_code   => $inst_code,
                   10253:                                      owner       => $course_owner,
                   10254:                                      type        => $crstype,
1.1029    raeburn  10255:                                      creator     => $env{'user.name'}.':'.
                   10256:                                                     $env{'user.domain'},
                   10257:                                      created     => $now,
                   10258:                                      context     => $context,
1.918     raeburn  10259:                                                 },
                   10260:                     };
1.921     raeburn  10261:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10262: # set toplevel url
1.271     www      10263:     my $topurl=$url;
                   10264:     unless ($nonstandard) {
                   10265: # ------------------------------------------ For standard courses, make top url
                   10266:         my $mapurl=&clutter($url);
1.278     www      10267:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10268:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10269: <map>
                   10270: <resource id="1" type="start"></resource>
                   10271: <resource id="2" src="$mapurl"></resource>
                   10272: <resource id="3" type="finish"></resource>
                   10273: <link index="1" from="1" to="2"></link>
                   10274: <link index="2" from="2" to="3"></link>
                   10275: </map>
                   10276: ENDINITMAP
                   10277:         $topurl=&declutter(
1.638     albertel 10278:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10279:                           );
                   10280:     }
                   10281: # ----------------------------------------------------------- Write preferences
1.84      www      10282:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10283:                      ('description'              => $description,
                   10284:                       'url'                      => $topurl,
                   10285:                       'internal.creator'         => $env{'user.name'}.':'.
                   10286:                                                     $env{'user.domain'},
                   10287:                       'internal.created'         => $now,
                   10288:                       'internal.creationcontext' => $context)
                   10289:                     );
1.84      www      10290:     return '/'.$udom.'/'.$uname;
                   10291: }
                   10292: 
1.1011    raeburn  10293: # ------------------------------------------------------------------- Create ID
                   10294: sub generate_coursenum {
1.1038    raeburn  10295:     my ($udom,$crstype) = @_;
1.1011    raeburn  10296:     my $domdesc = &domain($udom);
                   10297:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10298:     my $first;
                   10299:     if ($crstype eq 'Community') {
                   10300:         $first = '0';
                   10301:     } else {
                   10302:         $first = int(1+rand(9)); 
                   10303:     } 
                   10304:     my $uname=$first.
1.1011    raeburn  10305:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10306:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10307:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10308: # ----------------------------------------------- Make sure that does not exist
                   10309:     my $uhome=&homeserver($uname,$udom,'true');
                   10310:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10311:         if ($crstype eq 'Community') {
                   10312:             $first = '0';
                   10313:         } else {
                   10314:             $first = int(1+rand(9));
                   10315:         }
                   10316:         $uname=$first.
1.1011    raeburn  10317:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10318:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10319:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10320:         $uhome=&homeserver($uname,$udom,'true');
                   10321:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10322:             return 'error: unable to generate unique course-ID';
                   10323:         }
                   10324:     }
                   10325:     return $uname;
                   10326: }
                   10327: 
1.813     albertel 10328: sub is_course {
1.1167    droeschl 10329:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10330:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10331:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10332:     my $uhome=&homeserver($cnum,$cdom);
                   10333:     my $iscourse;
                   10334:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10335:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10336:     } else {
                   10337:         my $hashid = $cdom.':'.$cnum;
                   10338:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10339:         unless (defined($cached)) {
                   10340:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10341:                                         $cnum,undef,undef,'.');
                   10342:             $iscourse = 0;
                   10343:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10344:                 $iscourse = 1;
                   10345:             }
                   10346:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10347:         }
                   10348:     }
                   10349:     return unless($iscourse);
1.1167    droeschl 10350:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10351: }
                   10352: 
1.1015    raeburn  10353: sub store_userdata {
                   10354:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10355:     my $result;
1.1016    raeburn  10356:     if ($datakey ne '') {
1.1013    raeburn  10357:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10358:             if ($udom eq '' || $uname eq '') {
                   10359:                 $udom = $env{'user.domain'};
                   10360:                 $uname = $env{'user.name'};
                   10361:             }
                   10362:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10363:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10364:                 $result = 'error: no_host';
                   10365:             } else {
                   10366:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10367:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10368: 
                   10369:                 my $namevalue='';
                   10370:                 foreach my $key (keys(%{$storehash})) {
                   10371:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10372:                 }
                   10373:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10374:                 unless ($namespace eq 'courserequests') {
                   10375:                     $datakey = &escape($datakey);
                   10376:                 }
1.1105    raeburn  10377:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10378:                                   $namevalue,$uhome);
1.1013    raeburn  10379:             }
                   10380:         } else {
                   10381:             $result = 'error: data to store was not a hash reference'; 
                   10382:         }
                   10383:     } else {
                   10384:         $result= 'error: invalid requestkey'; 
                   10385:     }
                   10386:     return $result;
                   10387: }
                   10388: 
1.21      www      10389: # ---------------------------------------------------------- Assign Custom Role
                   10390: 
                   10391: sub assigncustomrole {
1.957     raeburn  10392:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10393:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10394:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10395: }
                   10396: 
                   10397: # ----------------------------------------------------------------- Revoke Role
                   10398: 
                   10399: sub revokerole {
1.957     raeburn  10400:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10401:     my $now=time;
1.965     raeburn  10402:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10403: }
                   10404: 
                   10405: # ---------------------------------------------------------- Revoke Custom Role
                   10406: 
                   10407: sub revokecustomrole {
1.957     raeburn  10408:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10409:     my $now=time;
1.357     www      10410:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10411:            $deleteflag,$selfenroll,$context);
1.17      www      10412: }
                   10413: 
1.533     banghart 10414: # ------------------------------------------------------------ Disk usage
1.535     albertel 10415: sub diskusage {
1.955     raeburn  10416:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10417:     $directorypath =~ s/\/$//;
                   10418:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10419:                        .&escape($getpropath).':'.&escape($uname).':'
                   10420:                        .&escape($udom),homeserver($uname,$udom));
                   10421:     if ($listing eq 'unknown_cmd') {
                   10422:         if ($getpropath) {
                   10423:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10424:         }
                   10425:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10426:     }
1.514     albertel 10427:     return $listing;
1.512     banghart 10428: }
                   10429: 
1.566     banghart 10430: sub is_locked {
1.1096    raeburn  10431:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10432:     my @check;
                   10433:     my $is_locked;
1.1093    raeburn  10434:     push (@check,$file_name);
1.613     albertel 10435:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10436: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10437:     my ($tmp)=keys(%locked);
                   10438:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10439:     
1.566     banghart 10440:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10441:         $is_locked = 'false';
                   10442:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10443:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10444:                $is_locked = 'true';
1.1096    raeburn  10445:                if (ref($which) eq 'ARRAY') {
                   10446:                    push(@{$which},$entry);
                   10447:                } else {
                   10448:                    last;
                   10449:                }
1.745     raeburn  10450:            }
                   10451:        }
1.566     banghart 10452:     } else {
                   10453:         $is_locked = 'false';
                   10454:     }
1.1093    raeburn  10455:     return $is_locked;
1.566     banghart 10456: }
                   10457: 
1.759     albertel 10458: sub declutter_portfile {
                   10459:     my ($file) = @_;
1.833     albertel 10460:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10461:     return $file;
                   10462: }
                   10463: 
1.559     banghart 10464: # ------------------------------------------------------------- Mark as Read Only
                   10465: 
                   10466: sub mark_as_readonly {
                   10467:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10468:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10469:     my ($tmp)=keys(%current_permissions);
                   10470:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10471:     foreach my $file (@{$files}) {
1.759     albertel 10472: 	$file = &declutter_portfile($file);
1.561     banghart 10473:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10474:     }
1.613     albertel 10475:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10476:     return;
                   10477: }
                   10478: 
1.572     banghart 10479: # ------------------------------------------------------------Save Selected Files
                   10480: 
                   10481: sub save_selected_files {
                   10482:     my ($user, $path, @files) = @_;
                   10483:     my $filename = $user."savedfiles";
1.573     banghart 10484:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10485:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10486:     foreach my $file (@files) {
1.620     albertel 10487:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10488:     }
                   10489:     foreach my $file (@other_files) {
1.574     banghart 10490:         print (OUT $file."\n");
1.572     banghart 10491:     }
1.574     banghart 10492:     close (OUT);
1.572     banghart 10493:     return 'ok';
                   10494: }
                   10495: 
1.574     banghart 10496: sub clear_selected_files {
                   10497:     my ($user) = @_;
                   10498:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10499:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10500:     print (OUT undef);
                   10501:     close (OUT);
                   10502:     return ("ok");    
                   10503: }
                   10504: 
1.572     banghart 10505: sub files_in_path {
                   10506:     my ($user, $path) = @_;
                   10507:     my $filename = $user."savedfiles";
                   10508:     my %return_files;
1.1172.2.96  raeburn  10509:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10510:     while (my $line_in = <IN>) {
1.574     banghart 10511:         chomp ($line_in);
                   10512:         my @paths_and_file = split (m!/!, $line_in);
                   10513:         my $file_part = pop (@paths_and_file);
                   10514:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10515:         $path_part.='/';
                   10516:         my $path_and_file = $path_part.$file_part;
                   10517:         if ($path_part eq $path) {
                   10518:             $return_files{$file_part}= 'selected';
                   10519:         }
                   10520:     }
1.574     banghart 10521:     close (IN);
                   10522:     return (\%return_files);
1.572     banghart 10523: }
                   10524: 
                   10525: # called in portfolio select mode, to show files selected NOT in current directory
                   10526: sub files_not_in_path {
                   10527:     my ($user, $path) = @_;
                   10528:     my $filename = $user."savedfiles";
                   10529:     my @return_files;
                   10530:     my $path_part;
1.1172.2.96  raeburn  10531:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10532:     while (my $line = <IN>) {
1.572     banghart 10533:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10534:         my @paths_and_file = split(m|/|, $line);
                   10535:         my $file_part = pop(@paths_and_file);
                   10536:         chomp($file_part);
                   10537:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10538:         $path_part .= '/';
                   10539:         my $path_and_file = $path_part.$file_part;
                   10540:         if ($path_part ne $path) {
1.800     albertel 10541:             push(@return_files, ($path_and_file));
1.572     banghart 10542:         }
                   10543:     }
1.800     albertel 10544:     close(OUT);
1.574     banghart 10545:     return (@return_files);
1.572     banghart 10546: }
                   10547: 
1.745     raeburn  10548: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10549: 
1.745     raeburn  10550: sub get_portfile_permissions {
                   10551:     my ($domain,$user) = @_;
1.613     albertel 10552:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10553:     my ($tmp)=keys(%current_permissions);
                   10554:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10555:     return \%current_permissions;
                   10556: }
                   10557: 
                   10558: #---------------------------------------------Get portfolio file access controls
                   10559: 
1.749     raeburn  10560: sub get_access_controls {
1.745     raeburn  10561:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10562:     my %access;
                   10563:     my $real_file = $file;
                   10564:     $file =~ s/\.meta$//;
1.745     raeburn  10565:     if (defined($file)) {
1.749     raeburn  10566:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10567:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10568:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10569:             }
                   10570:         }
1.745     raeburn  10571:     } else {
1.749     raeburn  10572:         foreach my $key (keys(%{$current_permissions})) {
                   10573:             if ($key =~ /\0accesscontrol$/) {
                   10574:                 if (defined($group)) {
                   10575:                     if ($key !~ m-^\Q$group\E/-) {
                   10576:                         next;
                   10577:                     }
                   10578:                 }
                   10579:                 my ($fullpath) = split(/\0/,$key);
                   10580:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10581:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10582:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10583:                     }
                   10584:                 }
                   10585:             }
                   10586:         }
                   10587:     }
                   10588:     return %access;
                   10589: }
                   10590: 
                   10591: sub modify_access_controls {
                   10592:     my ($file_name,$changes,$domain,$user)=@_;
                   10593:     my ($outcome,$deloutcome);
                   10594:     my %store_permissions;
                   10595:     my %new_values;
                   10596:     my %new_control;
                   10597:     my %translation;
                   10598:     my @deletions = ();
                   10599:     my $now = time;
                   10600:     if (exists($$changes{'activate'})) {
                   10601:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10602:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10603:             my $numnew = scalar(@newitems);
                   10604:             for (my $i=0; $i<$numnew; $i++) {
                   10605:                 my $newkey = $newitems[$i];
                   10606:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10607:                 if ($newkey =~ /^\d+:/) { 
                   10608:                     $newkey =~ s/^(\d+)/$newid/;
                   10609:                     $translation{$1} = $newid;
                   10610:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10611:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10612:                     $translation{$1} = $newid;
                   10613:                 }
1.749     raeburn  10614:                 $new_values{$file_name."\0".$newkey} = 
                   10615:                                           $$changes{'activate'}{$newitems[$i]};
                   10616:                 $new_control{$newkey} = $now;
                   10617:             }
                   10618:         }
                   10619:     }
                   10620:     my %todelete;
                   10621:     my %changed_items;
                   10622:     foreach my $action ('delete','update') {
                   10623:         if (exists($$changes{$action})) {
                   10624:             if (ref($$changes{$action}) eq 'HASH') {
                   10625:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10626:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10627:                     if ($action eq 'delete') { 
                   10628:                         $todelete{$itemnum} = 1;
                   10629:                     } else {
                   10630:                         $changed_items{$itemnum} = $key;
                   10631:                     }
                   10632:                 }
1.745     raeburn  10633:             }
                   10634:         }
1.749     raeburn  10635:     }
                   10636:     # get lock on access controls for file.
                   10637:     my $lockhash = {
                   10638:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10639:                                                        ':'.$env{'user.domain'},
                   10640:                    }; 
                   10641:     my $tries = 0;
                   10642:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10643:    
1.1172.2.79  raeburn  10644:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10645:         $tries ++;
1.1172.2.79  raeburn  10646:         sleep(0.1);
1.749     raeburn  10647:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10648:     }
                   10649:     if ($gotlock eq 'ok') {
                   10650:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10651:         my ($tmp)=keys(%curr_permissions);
                   10652:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10653:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10654:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10655:             if (ref($curr_controls) eq 'HASH') {
                   10656:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10657:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10658:                     if (defined($todelete{$itemnum})) {
                   10659:                         push(@deletions,$file_name."\0".$control_item);
                   10660:                     } else {
                   10661:                         if (defined($changed_items{$itemnum})) {
                   10662:                             $new_control{$changed_items{$itemnum}} = $now;
                   10663:                             push(@deletions,$file_name."\0".$control_item);
                   10664:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10665:                         } else {
                   10666:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10667:                         }
                   10668:                     }
1.745     raeburn  10669:                 }
                   10670:             }
                   10671:         }
1.970     raeburn  10672:         my ($group);
                   10673:         if (&is_course($domain,$user)) {
                   10674:             ($group,my $file) = split(/\//,$file_name,2);
                   10675:         }
1.749     raeburn  10676:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10677:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10678:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10679:         #  remove lock
                   10680:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10681:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10682:         my $sqlresult =
1.970     raeburn  10683:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10684:                                     $group);
1.749     raeburn  10685:     } else {
                   10686:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10687:     }
1.749     raeburn  10688:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10689: }
                   10690: 
1.827     raeburn  10691: sub make_public_indefinitely {
                   10692:     my ($requrl) = @_;
                   10693:     my $now = time;
                   10694:     my $action = 'activate';
                   10695:     my $aclnum = 0;
                   10696:     if (&is_portfolio_url($requrl)) {
                   10697:         my (undef,$udom,$unum,$file_name,$group) =
                   10698:             &parse_portfolio_url($requrl);
                   10699:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10700:         my %access_controls = &get_access_controls($current_perms,
                   10701:                                                    $group,$file_name);
                   10702:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10703:             my ($num,$scope,$end,$start) = 
                   10704:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10705:             if ($scope eq 'public') {
                   10706:                 if ($start <= $now && $end == 0) {
                   10707:                     $action = 'none';
                   10708:                 } else {
                   10709:                     $action = 'update';
                   10710:                     $aclnum = $num;
                   10711:                 }
                   10712:                 last;
                   10713:             }
                   10714:         }
                   10715:         if ($action eq 'none') {
                   10716:              return 'ok';
                   10717:         } else {
                   10718:             my %changes;
                   10719:             my $newend = 0;
                   10720:             my $newstart = $now;
                   10721:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10722:             $changes{$action}{$newkey} = {
                   10723:                 type => 'public',
                   10724:                 time => {
                   10725:                     start => $newstart,
                   10726:                     end   => $newend,
                   10727:                 },
                   10728:             };
                   10729:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10730:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10731:             return $outcome;
                   10732:         }
                   10733:     } else {
                   10734:         return 'invalid';
                   10735:     }
                   10736: }
                   10737: 
1.745     raeburn  10738: #------------------------------------------------------Get Marked as Read Only
                   10739: 
                   10740: sub get_marked_as_readonly {
                   10741:     my ($domain,$user,$what,$group) = @_;
                   10742:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10743:     my @readonly_files;
1.629     banghart 10744:     my $cmp1=$what;
                   10745:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10746:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10747:         if (defined($group)) {
                   10748:             if ($file_name !~ m-^\Q$group\E/-) {
                   10749:                 next;
                   10750:             }
                   10751:         }
1.561     banghart 10752:         if (ref($value) eq "ARRAY"){
                   10753:             foreach my $stored_what (@{$value}) {
1.629     banghart 10754:                 my $cmp2=$stored_what;
1.759     albertel 10755:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10756:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10757:                 }
1.629     banghart 10758:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10759:                     push(@readonly_files, $file_name);
1.745     raeburn  10760:                     last;
1.563     banghart 10761:                 } elsif (!defined($what)) {
                   10762:                     push(@readonly_files, $file_name);
1.745     raeburn  10763:                     last;
1.561     banghart 10764:                 }
                   10765:             }
1.745     raeburn  10766:         }
1.561     banghart 10767:     }
                   10768:     return @readonly_files;
                   10769: }
1.577     banghart 10770: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10771: 
1.577     banghart 10772: sub get_marked_as_readonly_hash {
1.745     raeburn  10773:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10774:     my %readonly_files;
1.745     raeburn  10775:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10776:         if (defined($group)) {
                   10777:             if ($file_name !~ m-^\Q$group\E/-) {
                   10778:                 next;
                   10779:             }
                   10780:         }
1.577     banghart 10781:         if (ref($value) eq "ARRAY"){
                   10782:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10783:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10784:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10785:                         if ($lock_descriptor eq 'graded') {
                   10786:                             $readonly_files{$file_name} = 'graded';
                   10787:                         } elsif ($lock_descriptor eq 'handback') {
                   10788:                             $readonly_files{$file_name} = 'handback';
                   10789:                         } else {
                   10790:                             if (!exists($readonly_files{$file_name})) {
                   10791:                                 $readonly_files{$file_name} = 'locked';
                   10792:                             }
                   10793:                         }
1.745     raeburn  10794:                     }
1.750     banghart 10795:                 } 
1.577     banghart 10796:             }
                   10797:         } 
                   10798:     }
                   10799:     return %readonly_files;
                   10800: }
1.559     banghart 10801: # ------------------------------------------------------------ Unmark as Read Only
                   10802: 
                   10803: sub unmark_as_readonly {
1.629     banghart 10804:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10805:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10806:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10807:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10808:     my $symb_crs = $what;
                   10809:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10810:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10811:     my ($tmp)=keys(%current_permissions);
                   10812:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10813:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10814:     foreach my $file (@readonly_files) {
1.759     albertel 10815: 	my $clean_file = &declutter_portfile($file);
                   10816: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10817: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10818:         my @new_locks;
                   10819:         my @del_keys;
                   10820:         if (ref($current_locks) eq "ARRAY"){
                   10821:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10822:                 my $compare=$locker;
1.749     raeburn  10823:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10824:                     $compare=join('',@{$locker});
1.746     raeburn  10825:                     if ($compare ne $symb_crs) {
                   10826:                         push(@new_locks, $locker);
                   10827:                     }
1.563     banghart 10828:                 }
                   10829:             }
1.650     albertel 10830:             if (scalar(@new_locks) > 0) {
1.563     banghart 10831:                 $current_permissions{$file} = \@new_locks;
                   10832:             } else {
                   10833:                 push(@del_keys, $file);
1.613     albertel 10834:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10835:                 delete($current_permissions{$file});
1.563     banghart 10836:             }
                   10837:         }
1.561     banghart 10838:     }
1.613     albertel 10839:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10840:     return;
                   10841: }
1.512     banghart 10842: 
1.17      www      10843: # ------------------------------------------------------------ Directory lister
                   10844: 
                   10845: sub dirlist {
1.955     raeburn  10846:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10847:     $uri=~s/^\///;
                   10848:     $uri=~s/\/$//;
1.253     stredwic 10849:     my ($udom, $uname);
1.955     raeburn  10850:     if ($getuserdir) {
1.253     stredwic 10851:         $udom = $userdomain;
                   10852:         $uname = $username;
1.955     raeburn  10853:     } else {
                   10854:         (undef,$udom,$uname)=split(/\//,$uri);
                   10855:         if(defined($userdomain)) {
                   10856:             $udom = $userdomain;
                   10857:         }
                   10858:         if(defined($username)) {
                   10859:             $uname = $username;
                   10860:         }
1.253     stredwic 10861:     }
1.955     raeburn  10862:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10863: 
1.955     raeburn  10864:     $dirRoot = $perlvar{'lonDocRoot'};
                   10865:     if (defined($getpropath)) {
                   10866:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10867:         $dirRoot =~ s/\/$//;
1.955     raeburn  10868:     } elsif (defined($getuserdir)) {
                   10869:         my $subdir=$uname.'__';
                   10870:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10871:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10872:                    ."/$udom/$subdir/$uname";
                   10873:     } elsif (defined($alternateRoot)) {
                   10874:         $dirRoot = $alternateRoot;
1.751     banghart 10875:     }
1.253     stredwic 10876: 
                   10877:     if($udom) {
                   10878:         if($uname) {
1.1135    raeburn  10879:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10880:             if ($uhome eq 'no_host') {
                   10881:                 return ([],'no_host');
                   10882:             }
1.955     raeburn  10883:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10884:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10885:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10886:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10887:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10888:             } else {
                   10889:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10890:             }
1.605     matthew  10891:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10892:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10893:                 @listing_results = split(/:/,$listing);
                   10894:             } else {
                   10895:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10896:             }
1.1135    raeburn  10897:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10898:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10899:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10900:                 return ([],$listing);
                   10901:             } else {
                   10902:                 return (\@listing_results);
1.1135    raeburn  10903:             }
1.955     raeburn  10904:         } elsif(!$alternateRoot) {
1.1136    raeburn  10905:             my (%allusers,%listerror);
1.841     albertel 10906: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10907:  	    foreach my $tryserver (keys(%servers)) {
                   10908:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10909:                                   &escape($udom),$tryserver);
                   10910:                 if ($listing eq 'unknown_cmd') {
                   10911: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10912: 				      $udom, $tryserver);
                   10913:                 } else {
                   10914:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10915:                 }
1.841     albertel 10916: 		if ($listing eq 'unknown_cmd') {
                   10917: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10918: 				      $udom, $tryserver);
                   10919: 		    @listing_results = split(/:/,$listing);
                   10920: 		} else {
                   10921: 		    @listing_results =
                   10922: 			map { &unescape($_); } split(/:/,$listing);
                   10923: 		}
1.1136    raeburn  10924:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10925:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10926:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10927:                     $listerror{$tryserver} = $listing;
                   10928:                 } else {
1.841     albertel 10929: 		    foreach my $line (@listing_results) {
                   10930: 			my ($entry) = split(/&/,$line,2);
                   10931: 			$allusers{$entry} = 1;
                   10932: 		    }
                   10933: 		}
1.253     stredwic 10934:             }
1.1136    raeburn  10935:             my @alluserslist=();
1.800     albertel 10936:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10937:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10938:             }
1.1172.2.80  raeburn  10939:             if (!%listerror) {
                   10940:                 # no errors
                   10941:                 return (\@alluserslist);
                   10942:             } elsif (scalar(keys(%servers)) == 1) {
                   10943:                 # one library server, one error
                   10944:                 my ($key) = keys(%listerror);
                   10945:                 return (\@alluserslist, $listerror{$key});
                   10946:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10947:                 # con_lost indicates that we might miss data from at least one
                   10948:                 # library server
                   10949:                 return (\@alluserslist, 'con_lost');
                   10950:             } else {
                   10951:                 # multiple library servers and no con_lost -> data should be
                   10952:                 # complete.
                   10953:                 return (\@alluserslist);
                   10954:             }
                   10955: 
1.253     stredwic 10956:         } else {
1.1136    raeburn  10957:             return ([],'missing username');
1.253     stredwic 10958:         }
1.955     raeburn  10959:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10960:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10961:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10962:         return (\@all_domains);
1.955     raeburn  10963:     } else {
1.1136    raeburn  10964:         return ([],'missing domain');
1.275     stredwic 10965:     }
                   10966: }
                   10967: 
                   10968: # --------------------------------------------- GetFileTimestamp
                   10969: # This function utilizes dirlist and returns the date stamp for
                   10970: # when it was last modified.  It will also return an error of -1
                   10971: # if an error occurs
                   10972: 
                   10973: sub GetFileTimestamp {
1.955     raeburn  10974:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10975:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10976:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10977:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10978:                                     undef,$getuserdir);
                   10979:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10980:         return -1;
                   10981:     }
                   10982:     if (ref($fileref) eq 'ARRAY') {
                   10983:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10984:         # @stats contains first the filename, then the stat output
                   10985:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10986:     } else {
                   10987:         return -1;
1.253     stredwic 10988:     }
1.26      www      10989: }
                   10990: 
1.712     albertel 10991: sub stat_file {
                   10992:     my ($uri) = @_;
1.787     albertel 10993:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10994: 
1.955     raeburn  10995:     my ($udom,$uname,$file);
1.712     albertel 10996:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10997: 	($udom,$uname,$file) =
1.811     albertel 10998: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10999: 	$file = 'userfiles/'.$file;
                   11000:     }
                   11001:     if ($uri =~ m-^/res/-) {
                   11002: 	($udom,$uname) = 
1.807     albertel 11003: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11004: 	$file = $uri;
                   11005:     }
                   11006: 
                   11007:     if (!$udom || !$uname || !$file) {
                   11008: 	# unable to handle the uri
                   11009: 	return ();
                   11010:     }
1.956     raeburn  11011:     my $getpropath;
                   11012:     if ($file =~ /^userfiles\//) {
                   11013:         $getpropath = 1;
                   11014:     }
1.1136    raeburn  11015:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11016:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11017:         return ();
                   11018:     } else {
                   11019:         if (ref($listref) eq 'ARRAY') {
                   11020:             my @stats = split('&',$listref->[0]);
                   11021: 	    shift(@stats); #filename is first
                   11022: 	    return @stats;
                   11023:         }
1.712     albertel 11024:     }
                   11025:     return ();
                   11026: }
                   11027: 
1.26      www      11028: # -------------------------------------------------------- Value of a Condition
                   11029: 
1.713     albertel 11030: # gets the value of a specific preevaluated condition
                   11031: #    stored in the string  $env{user.state.<cid>}
                   11032: # or looks up a condition reference in the bighash and if if hasn't
                   11033: # already been evaluated recurses into docondval to get the value of
                   11034: # the condition, then memoizing it to 
                   11035: #   $env{user.state.<cid>.<condition>}
1.40      www      11036: sub directcondval {
                   11037:     my $number=shift;
1.620     albertel 11038:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11039: 	&Apache::lonuserstate::evalstate();
                   11040:     }
1.713     albertel 11041:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11042: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11043:     } elsif ($number =~ /^_/) {
                   11044: 	my $sub_condition;
                   11045: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11046: 		&GDBM_READER(),0640)) {
                   11047: 	    $sub_condition=$bighash{'conditions'.$number};
                   11048: 	    untie(%bighash);
                   11049: 	}
                   11050: 	my $value = &docondval($sub_condition);
1.949     raeburn  11051: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11052: 	return $value;
                   11053:     }
1.620     albertel 11054:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11055:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11056:     } else {
                   11057:        return 2;
                   11058:     }
                   11059: }
                   11060: 
1.713     albertel 11061: # get the collection of conditions for this resource
1.26      www      11062: sub condval {
                   11063:     my $condidx=shift;
1.54      www      11064:     my $allpathcond='';
1.713     albertel 11065:     foreach my $cond (split(/\|/,$condidx)) {
                   11066: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11067: 	    $allpathcond.=
                   11068: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11069: 	}
1.191     harris41 11070:     }
1.54      www      11071:     $allpathcond=~s/\|$//;
1.713     albertel 11072:     return &docondval($allpathcond);
                   11073: }
                   11074: 
                   11075: #evaluates an expression of conditions
                   11076: sub docondval {
                   11077:     my ($allpathcond) = @_;
                   11078:     my $result=0;
                   11079:     if ($env{'request.course.id'}
                   11080: 	&& defined($allpathcond)) {
                   11081: 	my $operand='|';
                   11082: 	my @stack;
                   11083: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11084: 	    if ($chunk eq '(') {
                   11085: 		push @stack,($operand,$result);
                   11086: 	    } elsif ($chunk eq ')') {
                   11087: 		my $before=pop @stack;
                   11088: 		if (pop @stack eq '&') {
                   11089: 		    $result=$result>$before?$before:$result;
                   11090: 		} else {
                   11091: 		    $result=$result>$before?$result:$before;
                   11092: 		}
                   11093: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11094: 		$operand=$chunk;
                   11095: 	    } else {
                   11096: 		my $new=directcondval($chunk);
                   11097: 		if ($operand eq '&') {
                   11098: 		    $result=$result>$new?$new:$result;
                   11099: 		} else {
                   11100: 		    $result=$result>$new?$result:$new;
                   11101: 		}
                   11102: 	    }
                   11103: 	}
1.26      www      11104:     }
                   11105:     return $result;
1.421     albertel 11106: }
                   11107: 
                   11108: # ---------------------------------------------------- Devalidate courseresdata
                   11109: 
                   11110: sub devalidatecourseresdata {
                   11111:     my ($coursenum,$coursedomain)=@_;
                   11112:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11113:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11114: }
                   11115: 
1.763     www      11116: 
1.200     www      11117: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11118: #
                   11119: #  Parameters:
                   11120: #      $coursenum    - Number of the course.
                   11121: #      $coursedomain - Domain at which the course was created.
                   11122: #  Returns:
                   11123: #     A hash of the course parameters along (I think) with timestamps
                   11124: #     and version info.
1.877     foxr     11125: 
1.624     albertel 11126: sub get_courseresdata {
                   11127:     my ($coursenum,$coursedomain)=@_;
1.200     www      11128:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11129:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11130:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11131:     my %dumpreply;
1.417     albertel 11132:     unless (defined($cached)) {
1.624     albertel 11133: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11134: 	$result=\%dumpreply;
1.251     albertel 11135: 	my ($tmp) = keys(%dumpreply);
                   11136: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11137: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11138: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11139: 	    return $tmp;
1.416     albertel 11140: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11141: 	    $result=undef;
1.599     albertel 11142: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11143: 	}
                   11144:     }
1.624     albertel 11145:     return $result;
                   11146: }
                   11147: 
1.633     albertel 11148: sub devalidateuserresdata {
                   11149:     my ($uname,$udom)=@_;
                   11150:     my $hashid="$udom:$uname";
                   11151:     &devalidate_cache_new('userres',$hashid);
                   11152: }
                   11153: 
1.624     albertel 11154: sub get_userresdata {
                   11155:     my ($uname,$udom)=@_;
                   11156:     #most student don\'t have any data set, check if there is some data
                   11157:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11158: 
                   11159:     my $hashid="$udom:$uname";
                   11160:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11161:     if (!defined($cached)) {
                   11162: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11163: 	$result=\%resourcedata;
                   11164: 	&do_cache_new('userres',$hashid,$result,600);
                   11165:     }
                   11166:     my ($tmp)=keys(%$result);
                   11167:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11168: 	return $result;
                   11169:     }
                   11170:     #error 2 occurs when the .db doesn't exist
                   11171:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11172:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11173: 	    &logthis("<font color=\"blue\">WARNING:".
                   11174: 		     " Trying to get resource data for ".
                   11175: 		     $uname." at ".$udom.": ".
                   11176: 		     $tmp."</font>");
                   11177:         }
1.624     albertel 11178:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11179: 	#&EXT_cache_set($udom,$uname);
                   11180: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11181: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11182:     }
                   11183:     return $tmp;
                   11184: }
1.879     foxr     11185: #----------------------------------------------- resdata - return resource data
                   11186: #  Purpose:
                   11187: #    Return resource data for either users or for a course.
                   11188: #  Parameters:
                   11189: #     $name      - Course/user name.
                   11190: #     $domain    - Name of the domain the user/course is registered on.
                   11191: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11192: #     @which     - Array of names of resources desired.
                   11193: #  Returns:
                   11194: #     The value of the first reasource in @which that is found in the
                   11195: #     resource hash.
                   11196: #  Exceptional Conditions:
                   11197: #     If the $type passed in is not valid (not the string 'course' or 
                   11198: #     'user', an undefined  reference is returned.
                   11199: #     If none of the resources are found, an undef is returned
1.624     albertel 11200: sub resdata {
                   11201:     my ($name,$domain,$type,@which)=@_;
                   11202:     my $result;
                   11203:     if ($type eq 'course') {
                   11204: 	$result=&get_courseresdata($name,$domain);
                   11205:     } elsif ($type eq 'user') {
                   11206: 	$result=&get_userresdata($name,$domain);
                   11207:     }
                   11208:     if (!ref($result)) { return $result; }    
1.251     albertel 11209:     foreach my $item (@which) {
1.927     albertel 11210: 	if (defined($result->{$item->[0]})) {
                   11211: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11212: 	}
1.250     albertel 11213:     }
1.291     albertel 11214:     return undef;
1.200     www      11215: }
                   11216: 
1.1172.2.31  raeburn  11217: sub get_numsuppfiles {
                   11218:     my ($cnum,$cdom,$ignorecache)=@_;
                   11219:     my $hashid=$cnum.':'.$cdom;
                   11220:     my ($suppcount,$cached);
                   11221:     unless ($ignorecache) {
                   11222:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11223:     }
                   11224:     unless (defined($cached)) {
                   11225:         my $chome=&homeserver($cnum,$cdom);
                   11226:         unless ($chome eq 'no_host') {
                   11227:             ($suppcount,my $errors) = (0,0);
                   11228:             my $suppmap = 'supplemental.sequence';
                   11229:             ($suppcount,$errors) =
                   11230:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11231:         }
                   11232:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11233:     }
                   11234:     return $suppcount;
                   11235: }
                   11236: 
1.379     matthew  11237: #
                   11238: # EXT resource caching routines
                   11239: #
                   11240: 
                   11241: sub clear_EXT_cache_status {
1.383     albertel 11242:     &delenv('cache.EXT.');
1.379     matthew  11243: }
                   11244: 
                   11245: sub EXT_cache_status {
                   11246:     my ($target_domain,$target_user) = @_;
1.383     albertel 11247:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11248:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11249:         # We know already the user has no data
                   11250:         return 1;
                   11251:     } else {
                   11252:         return 0;
                   11253:     }
                   11254: }
                   11255: 
                   11256: sub EXT_cache_set {
                   11257:     my ($target_domain,$target_user) = @_;
1.383     albertel 11258:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11259:     #&appenv({$cachename => time});
1.379     matthew  11260: }
                   11261: 
1.28      www      11262: # --------------------------------------------------------- Value of a Variable
1.58      www      11263: sub EXT {
1.715     albertel 11264: 
1.1172.2.28  raeburn  11265:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11266:     unless ($varname) { return ''; }
1.218     albertel 11267:     #get real user name/domain, courseid and symb
                   11268:     my $courseid;
1.359     albertel 11269:     my $publicuser;
1.427     www      11270:     if ($symbparm) {
                   11271: 	$symbparm=&get_symb_from_alias($symbparm);
                   11272:     }
1.218     albertel 11273:     if (!($uname && $udom)) {
1.790     albertel 11274:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11275:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11276:     } else {
1.620     albertel 11277: 	$courseid=$env{'request.course.id'};
1.218     albertel 11278:     }
1.48      www      11279:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11280:     my $rest;
1.320     albertel 11281:     if (defined($therest[0])) {
1.48      www      11282:        $rest=join('.',@therest);
                   11283:     } else {
                   11284:        $rest='';
                   11285:     }
1.320     albertel 11286: 
1.57      www      11287:     my $qualifierrest=$qualifier;
                   11288:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11289:     my $spacequalifierrest=$space;
                   11290:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11291:     if ($realm eq 'user') {
1.48      www      11292: # --------------------------------------------------------------- user.resource
                   11293: 	if ($space eq 'resource') {
1.651     albertel 11294: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11295: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11296: 		 &&
1.744     albertel 11297: 		 ($symbparm eq &symbread()) ) {	
                   11298: 		# if we are in the middle of processing the resource the
                   11299: 		# get the value we are planning on committing
                   11300:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11301:                     return $Apache::lonhomework::results{$qualifierrest};
                   11302:                 } else {
                   11303:                     return $Apache::lonhomework::history{$qualifierrest};
                   11304:                 }
1.335     albertel 11305: 	    } else {
1.359     albertel 11306: 		my %restored;
1.620     albertel 11307: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11308: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11309: 		} else {
                   11310: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11311: 		}
1.335     albertel 11312: 		return $restored{$qualifierrest};
                   11313: 	    }
1.48      www      11314: # ----------------------------------------------------------------- user.access
                   11315:         } elsif ($space eq 'access') {
1.218     albertel 11316: 	    # FIXME - not supporting calls for a specific user
1.48      www      11317:             return &allowed($qualifier,$rest);
                   11318: # ------------------------------------------ user.preferences, user.environment
                   11319:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11320: 	    if (($uname eq $env{'user.name'}) &&
                   11321: 		($udom eq $env{'user.domain'})) {
                   11322: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11323: 	    } else {
1.359     albertel 11324: 		my %returnhash;
                   11325: 		if (!$publicuser) {
                   11326: 		    %returnhash=&userenvironment($udom,$uname,
                   11327: 						 $qualifierrest);
                   11328: 		}
1.218     albertel 11329: 		return $returnhash{$qualifierrest};
                   11330: 	    }
1.48      www      11331: # ----------------------------------------------------------------- user.course
                   11332:         } elsif ($space eq 'course') {
1.218     albertel 11333: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11334:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11335: # ------------------------------------------------------------------- user.role
                   11336:         } elsif ($space eq 'role') {
1.218     albertel 11337: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11338:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11339:             if ($qualifier eq 'value') {
                   11340: 		return $role;
                   11341:             } elsif ($qualifier eq 'extent') {
                   11342:                 return $where;
                   11343:             }
                   11344: # ----------------------------------------------------------------- user.domain
                   11345:         } elsif ($space eq 'domain') {
1.218     albertel 11346:             return $udom;
1.48      www      11347: # ------------------------------------------------------------------- user.name
                   11348:         } elsif ($space eq 'name') {
1.218     albertel 11349:             return $uname;
1.48      www      11350: # ---------------------------------------------------- Any other user namespace
1.29      www      11351:         } else {
1.359     albertel 11352: 	    my %reply;
                   11353: 	    if (!$publicuser) {
                   11354: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11355: 	    }
                   11356: 	    return $reply{$qualifierrest};
1.48      www      11357:         }
1.236     www      11358:     } elsif ($realm eq 'query') {
                   11359: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11360:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11361: 						[$spacequalifierrest]);
1.620     albertel 11362: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11363:    } elsif ($realm eq 'request') {
1.48      www      11364: # ------------------------------------------------------------- request.browser
                   11365:         if ($space eq 'browser') {
1.1145    bisitz   11366:             return $env{'browser.'.$qualifier};
1.57      www      11367: # ------------------------------------------------------------ request.filename
                   11368:         } else {
1.620     albertel 11369:             return $env{'request.'.$spacequalifierrest};
1.29      www      11370:         }
1.28      www      11371:     } elsif ($realm eq 'course') {
1.48      www      11372: # ---------------------------------------------------------- course.description
1.620     albertel 11373:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11374:     } elsif ($realm eq 'resource') {
1.165     www      11375: 
1.620     albertel 11376: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11377: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11378: 	}
1.693     albertel 11379: 
1.1172.2.30  raeburn  11380:         if ($qualifier eq '') {
                   11381: 	    if ($space eq 'title') {
                   11382: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11383: 	        return &gettitle($symbparm);
                   11384: 	    }
1.693     albertel 11385: 	
1.1172.2.30  raeburn  11386: 	    if ($space eq 'map') {
                   11387: 	        my ($map) = &decode_symb($symbparm);
                   11388: 	        return &symbread($map);
                   11389: 	    }
                   11390:             if ($space eq 'maptitle') {
                   11391:                 my ($map) = &decode_symb($symbparm);
                   11392:                 return &gettitle($map);
                   11393:             }
                   11394: 	    if ($space eq 'filename') {
                   11395: 	        if ($symbparm) {
                   11396: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11397: 	        }
                   11398: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11399: 	    }
1.1172.2.30  raeburn  11400: 
                   11401:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11402:                 if ($space eq 'visibleparts') {
                   11403:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11404:                     my $item;
                   11405:                     if (ref($navmap)) {
                   11406:                         my $res = $navmap->getBySymb($symbparm);
                   11407:                         my $parts = $res->parts();
                   11408:                         if (ref($parts) eq 'ARRAY') {
                   11409:                             $item = join(',',@{$parts});
                   11410:                         }
                   11411:                         undef($navmap);
                   11412:                     }
                   11413:                     return $item;
                   11414:                 }
                   11415:             }
                   11416:         }
1.693     albertel 11417: 
                   11418: 	my ($section, $group, @groups);
1.593     albertel 11419: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11420:         if (($courseid eq '') && ($cid)) {
                   11421:             $courseid = $cid;
                   11422:         }
                   11423: 	if (($symbparm && $courseid) && 
                   11424: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11425: 
1.218     albertel 11426: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11427: 
1.60      www      11428: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11429: 	    my $symbp=$symbparm;
1.735     albertel 11430: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11431: 
                   11432: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11433: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11434: 
1.620     albertel 11435: 	    if (($env{'user.name'} eq $uname) &&
                   11436: 		($env{'user.domain'} eq $udom)) {
                   11437: 		$section=$env{'request.course.sec'};
1.733     raeburn  11438:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11439:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11440: 	    } else {
1.539     albertel 11441: 		if (! defined($usection)) {
1.551     albertel 11442: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11443: 		} else {
                   11444: 		    $section = $usection;
                   11445: 		}
1.733     raeburn  11446:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11447: 	    }
                   11448: 
                   11449: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11450: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11451: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11452: 
1.593     albertel 11453: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11454: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11455: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11456: 
1.60      www      11457: # ----------------------------------------------------------- first, check user
1.624     albertel 11458: 
                   11459: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11460: 				       ([$courselevelr,'resource'],
                   11461: 					[$courselevelm,'map'     ],
                   11462: 					[$courselevel, 'course'  ]));
1.931     albertel 11463: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11464: 
1.594     albertel 11465: # ------------------------------------------------ second, check some of course
1.684     raeburn  11466:             my $coursereply;
1.691     raeburn  11467:             if (@groups > 0) {
                   11468:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11469:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11470:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11471:             }
1.96      www      11472: 
1.684     raeburn  11473: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11474: 				  $env{'course.'.$courseid.'.domain'},
                   11475: 				  'course',
                   11476: 				  ([$seclevelr,   'resource'],
                   11477: 				   [$seclevelm,   'map'     ],
                   11478: 				   [$seclevel,    'course'  ],
                   11479: 				   [$courselevelr,'resource']));
                   11480: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11481: 
1.60      www      11482: # ------------------------------------------------------ third, check map parms
1.218     albertel 11483: 	    my %parmhash=();
                   11484: 	    my $thisparm='';
                   11485: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11486: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11487: 		    &GDBM_READER(),0640)) {
1.218     albertel 11488: 		$thisparm=$parmhash{$symbparm};
                   11489: 		untie(%parmhash);
                   11490: 	    }
1.927     albertel 11491: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11492: 	}
1.594     albertel 11493: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11494: 
1.218     albertel 11495: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11496: 	my $filename;
                   11497: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11498: 	if ($symbparm) {
1.409     www      11499: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11500: 	} else {
1.620     albertel 11501: 	    $filename=$env{'request.filename'};
1.282     albertel 11502: 	}
                   11503: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11504: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11505: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11506: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11507: 
1.927     albertel 11508: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11509: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11510: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11511: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11512: 				     $env{'course.'.$courseid.'.domain'},
                   11513: 				     'course',
1.927     albertel 11514: 				     ([$courselevelm,'map'   ],
                   11515: 				      [$courselevel, 'course']));
                   11516: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11517: 	}
1.145     www      11518: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11519: 	unless ($space eq '0') {
1.336     albertel 11520: 	    my @parts=split(/_/,$space);
                   11521: 	    my $id=pop(@parts);
                   11522: 	    my $part=join('_',@parts);
                   11523: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11524: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11525: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11526: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11527: 	}
1.395     albertel 11528: 	if ($recurse) { return undef; }
                   11529: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11530: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11531: # ---------------------------------------------------- Any other user namespace
                   11532:     } elsif ($realm eq 'environment') {
                   11533: # ----------------------------------------------------------------- environment
1.620     albertel 11534: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11535: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11536: 	} else {
1.770     albertel 11537: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11538: 		return '';
                   11539: 	    }
1.219     albertel 11540: 	    my %returnhash=&userenvironment($udom,$uname,
                   11541: 					    $spacequalifierrest);
                   11542: 	    return $returnhash{$spacequalifierrest};
                   11543: 	}
1.28      www      11544:     } elsif ($realm eq 'system') {
1.48      www      11545: # ----------------------------------------------------------------- system.time
                   11546: 	if ($space eq 'time') {
                   11547: 	    return time;
                   11548:         }
1.696     albertel 11549:     } elsif ($realm eq 'server') {
                   11550: # ----------------------------------------------------------------- system.time
                   11551: 	if ($space eq 'name') {
                   11552: 	    return $ENV{'SERVER_NAME'};
                   11553:         }
1.28      www      11554:     }
1.48      www      11555:     return '';
1.61      www      11556: }
                   11557: 
1.927     albertel 11558: sub get_reply {
                   11559:     my ($reply_value) = @_;
1.940     raeburn  11560:     if (ref($reply_value) eq 'ARRAY') {
                   11561:         if (wantarray) {
                   11562: 	    return @$reply_value;
                   11563:         }
                   11564:         return $reply_value->[0];
                   11565:     } else {
                   11566:         return $reply_value;
1.927     albertel 11567:     }
                   11568: }
                   11569: 
1.691     raeburn  11570: sub check_group_parms {
                   11571:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11572:     my @groupitems = ();
                   11573:     my $resultitem;
1.927     albertel 11574:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11575:     foreach my $group (@{$groups}) {
                   11576:         foreach my $level (@levels) {
1.927     albertel 11577:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11578:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11579:         }
                   11580:     }
                   11581:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11582:                             $env{'course.'.$courseid.'.domain'},
                   11583:                                      'course',@groupitems);
                   11584:     return $coursereply;
                   11585: }
                   11586: 
                   11587: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11588:     my ($courseid,@groups) = @_;
                   11589:     @groups = sort(@groups);
1.691     raeburn  11590:     return @groups;
                   11591: }
                   11592: 
1.395     albertel 11593: sub packages_tab_default {
                   11594:     my ($uri,$varname)=@_;
                   11595:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11596: 
                   11597:     my (@extension,@specifics,$do_default);
                   11598:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11599: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11600: 	if ($pack_type eq 'default') {
                   11601: 	    $do_default=1;
                   11602: 	} elsif ($pack_type eq 'extension') {
                   11603: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11604: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11605: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11606: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11607: 	}
                   11608:     }
                   11609:     # first look for a package that matches the requested part id
                   11610:     foreach my $package (@specifics) {
                   11611: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11612: 	next if ($pack_part ne $part);
                   11613: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11614: 	    return $packagetab{"$pack_type&$name&default"};
                   11615: 	}
                   11616:     }
                   11617:     # look for any possible matching non extension_ package
                   11618:     foreach my $package (@specifics) {
                   11619: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11620: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11621: 	    return $packagetab{"$pack_type&$name&default"};
                   11622: 	}
1.585     albertel 11623: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11624: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11625: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11626: 	}
                   11627:     }
1.738     albertel 11628:     # look for any posible extension_ match
                   11629:     foreach my $package (@extension) {
                   11630: 	my ($package,$pack_type)=@{$package};
                   11631: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11632: 	    return $packagetab{"$pack_type&$name&default"};
                   11633: 	}
                   11634: 	if (defined($packagetab{$package."&$name&default"})) {
                   11635: 	    return $packagetab{$package."&$name&default"};
                   11636: 	}
                   11637:     }
                   11638:     # look for a global default setting
                   11639:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11640: 	return $packagetab{"default&$name&default"};
                   11641:     }
1.395     albertel 11642:     return undef;
                   11643: }
                   11644: 
1.334     albertel 11645: sub add_prefix_and_part {
                   11646:     my ($prefix,$part)=@_;
                   11647:     my $keyroot;
                   11648:     if (defined($prefix) && $prefix !~ /^__/) {
                   11649: 	# prefix that has a part already
                   11650: 	$keyroot=$prefix;
                   11651:     } elsif (defined($prefix)) {
                   11652: 	# prefix that is missing a part
                   11653: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11654:     } else {
                   11655: 	# no prefix at all
                   11656: 	if (defined($part)) { $keyroot='_'.$part; }
                   11657:     }
                   11658:     return $keyroot;
                   11659: }
                   11660: 
1.71      www      11661: # ---------------------------------------------------------------- Get metadata
                   11662: 
1.599     albertel 11663: my %metaentry;
1.1070    www      11664: my %importedpartids;
1.1172.2.99  raeburn  11665: my %importedrespids;
1.71      www      11666: sub metadata {
1.176     www      11667:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11668:     $uri=&declutter($uri);
1.288     albertel 11669:     # if it is a non metadata possible uri return quickly
1.529     albertel 11670:     if (($uri eq '') || 
                   11671: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11672: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11673:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11674: 	return undef;
                   11675:     }
1.1172.2.49  raeburn  11676:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11677: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11678: 	return undef;
1.288     albertel 11679:     }
1.73      www      11680:     my $filename=$uri;
                   11681:     $uri=~s/\.meta$//;
1.172     www      11682: #
                   11683: # Is the metadata already cached?
1.177     www      11684: # Look at timestamp of caching
1.172     www      11685: # Everything is cached by the main uri, libraries are never directly cached
                   11686: #
1.428     albertel 11687:     if (!defined($liburi)) {
1.599     albertel 11688: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11689: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11690:     }
                   11691:     {
1.1069    www      11692: # Imported parts would go here
1.1172.2.99  raeburn  11693:         my @origfiletagids=();
1.1069    www      11694:         my $importedparts=0;
1.1172.2.99  raeburn  11695: 
                   11696: # Imported responseids would go here
                   11697:         my $importedresponses=0;
1.172     www      11698: #
                   11699: # Is this a recursive call for a library?
                   11700: #
1.599     albertel 11701: #	if (! exists($metacache{$uri})) {
                   11702: #	    $metacache{$uri}={};
                   11703: #	}
1.924     albertel 11704: 	my $cachetime = 60*60;
1.171     www      11705:         if ($liburi) {
                   11706: 	    $liburi=&declutter($liburi);
                   11707:             $filename=$liburi;
1.401     bowersj2 11708:         } else {
1.599     albertel 11709: 	    &devalidate_cache_new('meta',$uri);
                   11710: 	    undef(%metaentry);
1.401     bowersj2 11711: 	}
1.140     www      11712:         my %metathesekeys=();
1.73      www      11713:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11714: 	my $metastring;
1.1140    www      11715: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11716: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11717: 	    $metastring = 
1.929     albertel 11718: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11719: 					  ('grade_target' => 'meta'));
                   11720: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11721: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11722:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11723: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11724: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11725: 	    $metastring=&getfile($file);
1.489     albertel 11726: 	}
1.208     albertel 11727:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11728:         my $token;
1.140     www      11729:         undef %metathesekeys;
1.71      www      11730:         while ($token=$parser->get_token) {
1.339     albertel 11731: 	    if ($token->[0] eq 'S') {
                   11732: 		if (defined($token->[2]->{'package'})) {
1.172     www      11733: #
                   11734: # This is a package - get package info
                   11735: #
1.339     albertel 11736: 		    my $package=$token->[2]->{'package'};
                   11737: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11738: 		    if (defined($token->[2]->{'id'})) { 
                   11739: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11740: 		    }
1.599     albertel 11741: 		    if ($metaentry{':packages'}) {
                   11742: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11743: 		    } else {
1.599     albertel 11744: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11745: 		    }
1.736     albertel 11746: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11747: 			my $part=$keyroot;
                   11748: 			$part=~s/^\_//;
1.736     albertel 11749: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11750: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11751: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11752: 			    # ignore package.tab specified default values
                   11753:                             # here &package_tab_default() will fetch those
                   11754: 			    if ($subp eq 'default') { next; }
1.736     albertel 11755: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11756: 			    my $unikey;
                   11757: 			    if ($pack =~ /_0$/) {
                   11758: 				$unikey='parameter_0_'.$name;
                   11759: 				$part=0;
                   11760: 			    } else {
                   11761: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11762: 			    }
1.339     albertel 11763: 			    if ($subp eq 'display') {
                   11764: 				$value.=' [Part: '.$part.']';
                   11765: 			    }
1.599     albertel 11766: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11767: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11768: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11769: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11770: 			    }
1.599     albertel 11771: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11772: 				$metaentry{':'.$unikey}=
                   11773: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11774: 			    }
1.339     albertel 11775: 			}
                   11776: 		    }
                   11777: 		} else {
1.172     www      11778: #
                   11779: # This is not a package - some other kind of start tag
1.339     albertel 11780: #
                   11781: 		    my $entry=$token->[1];
1.1068    www      11782: 		    my $unikey='';
1.175     www      11783: 
1.339     albertel 11784: 		    if ($entry eq 'import') {
1.175     www      11785: #
                   11786: # Importing a library here
1.339     albertel 11787: #
1.1067    www      11788:                         my $location=$parser->get_text('/import');
                   11789:                         my $dir=$filename;
                   11790:                         $dir=~s|[^/]*$||;
                   11791:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11792: 
                   11793:                         my $importid=$token->[2]->{'id'};
1.1068    www      11794:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11795: #
                   11796: # Check metadata for imported file to
                   11797: # see if it contained response items
                   11798: #
                   11799:                         my %currmetaentry = %metaentry;
                   11800:                         my $libresponseorder = &metadata($location,'responseorder');
                   11801:                         my $origfile;
                   11802:                         if ($libresponseorder ne '') {
                   11803:                             if ($#origfiletagids<0) {
                   11804:                                 undef(%importedrespids);
                   11805:                                 undef(%importedpartids);
                   11806:                             }
                   11807:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11808:                             if (@{$importedrespids{$importid}} > 0) {
                   11809:                                 $importedresponses = 1;
                   11810: # We need to get the original file and the imported file to get the response order correct
                   11811: # Load and inspect original file
                   11812:                                 if ($#origfiletagids<0) {
                   11813:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11814:                                     $origfile=&getfile($origfilelocation);
                   11815:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11816:                                 }
                   11817:                             }
                   11818:                         }
                   11819: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11820: # hash populated for imported library file
                   11821:                         %metaentry = %currmetaentry;
                   11822:                         undef(%currmetaentry);
1.1068    www      11823:                         if ($importmode eq 'problem') {
1.1069    www      11824: # Import as problem/response
1.1068    www      11825:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11826:                         } elsif ($importmode eq 'part') {
                   11827: # Import as part(s)
1.1069    www      11828:                            $importedparts=1;
                   11829: # We need to get the original file and the imported file to get the part order correct
                   11830: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11831: # Load and inspect original file if we didn't do that already
                   11832:                            if ($#origfiletagids<0) {
                   11833:                                undef(%importedrespids);
                   11834:                                undef(%importedpartids);
                   11835:                                if ($origfile eq '') {
                   11836:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11837:                                    $origfile=&getfile($origfilelocation);
                   11838:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11839:                                }
1.1070    www      11840:                            }
                   11841: 
1.1069    www      11842: # Load and inspect imported file
                   11843:                            my $impfile=&getfile($location);
                   11844:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11845:                            if ($#impfilepartids>=0) {
                   11846: # This problem had parts
1.1070    www      11847:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11848:                            } else {
                   11849: # Importing by turning a single problem into a problem part
                   11850: # It gets the import-tags ID as part-ID
                   11851:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11852:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11853:                            }
1.1068    www      11854:                         } else {
                   11855: # Normal import
                   11856:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11857:                            if (defined($token->[2]->{'id'})) {
                   11858:                               $unikey.='_'.$token->[2]->{'id'};
                   11859:                            }
1.1067    www      11860:                         }
                   11861: 
1.339     albertel 11862: 			if ($depthcount<20) {
1.736     albertel 11863: 			    my $metadata = 
                   11864: 				&metadata($uri,'keys', $location,$unikey,
                   11865: 					  $depthcount+1);
                   11866: 			    foreach my $meta (split(',',$metadata)) {
                   11867: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11868: 				$metathesekeys{$meta}=1;
1.339     albertel 11869: 			    }
1.1068    www      11870: 			
                   11871:                         }
1.1067    www      11872: 		    } else {
                   11873: #
                   11874: # Not importing, some other kind of non-package, non-library start tag
                   11875: # 
                   11876:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11877:                         if (defined($token->[2]->{'id'})) {
                   11878:                             $unikey.='_'.$token->[2]->{'id'};
                   11879:                         }
1.339     albertel 11880: 			if (defined($token->[2]->{'name'})) { 
                   11881: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11882: 			}
                   11883: 			$metathesekeys{$unikey}=1;
1.736     albertel 11884: 			foreach my $param (@{$token->[3]}) {
                   11885: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11886: 				$token->[2]->{$param};
1.339     albertel 11887: 			}
                   11888: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11889: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11890: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11891: 		 # only ws inside the tag, and not in default, so use default
                   11892: 		 # as value
1.599     albertel 11893: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11894: 			} elsif ( $internaltext =~ /\S/ ) {
                   11895: 		  # something interesting inside the tag
                   11896: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11897: 			} else {
1.908     albertel 11898: 		  # no interesting values, don't set a default
1.339     albertel 11899: 			}
1.172     www      11900: # end of not-a-package not-a-library import
1.339     albertel 11901: 		    }
1.172     www      11902: # end of not-a-package start tag
1.339     albertel 11903: 		}
1.172     www      11904: # the next is the end of "start tag"
1.339     albertel 11905: 	    }
                   11906: 	}
1.483     albertel 11907: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11908: 	$extension = lc($extension);
                   11909: 	if ($extension eq 'htm') { $extension='html'; }
                   11910: 
1.737     albertel 11911: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11912: 	    #no specific packages #how's our extension
                   11913: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11914: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11915: 					 \%metathesekeys);
                   11916: 	}
1.883     albertel 11917: 
                   11918: 	if (!exists($metaentry{':packages'})
                   11919: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11920: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11921: 		#no specific packages well let's get default then
                   11922: 		if ($key!~/^default&/) { next; }
1.488     albertel 11923: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11924: 					     \%metathesekeys);
                   11925: 	    }
                   11926: 	}
1.338     www      11927: # are there custom rights to evaluate
1.599     albertel 11928: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11929: 
1.338     www      11930:     #
                   11931:     # Importing a rights file here
1.339     albertel 11932:     #
                   11933: 	    unless ($depthcount) {
1.599     albertel 11934: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11935: 		my $dir=$filename;
                   11936: 		$dir=~s|[^/]*$||;
                   11937: 		$location=&filelocation($dir,$location);
1.736     albertel 11938: 		my $rights_metadata =
                   11939: 		    &metadata($uri,'keys',$location,'_rights',
                   11940: 			      $depthcount+1);
                   11941: 		foreach my $rights (split(',',$rights_metadata)) {
                   11942: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11943: 		    $metathesekeys{$rights}=1;
1.339     albertel 11944: 		}
                   11945: 	    }
                   11946: 	}
1.737     albertel 11947: 	# uniqifiy package listing
                   11948: 	my %seen;
                   11949: 	my @uniq_packages =
                   11950: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11951: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11952: 
1.1172.2.99  raeburn  11953:         if (($importedresponses) || ($importedparts)) {
                   11954:             if ($importedparts) {
1.1070    www      11955: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11956:                 $metaentry{':partorder'}='';
                   11957:                 $metathesekeys{'partorder'}=1;
                   11958:             }
                   11959:             if ($importedresponses) {
                   11960: # We had imported responses and need to rebuild responseorder
                   11961:                 $metaentry{':responseorder'}='';
                   11962:                 $metathesekeys{'responseorder'}=1;
                   11963:             }
                   11964:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11965:                 my $origid = $origfiletagids[$index+1];
                   11966:                 if ($origfiletagids[$index] eq 'part') {
                   11967: # Original part, part of the problem
                   11968:                     if ($importedparts) {
                   11969:                         $metaentry{':partorder'}.=','.$origid;
                   11970:                     }
                   11971:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11972:                     if ($importedparts) {
                   11973: # We have imported parts at this position
                   11974:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11975:                     }
                   11976:                     if ($importedresponses) {
                   11977: # We have imported responses at this position
                   11978:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11979:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11980:                         }
                   11981:                     }
                   11982:                 } else {
                   11983: # Original response item, part of the problem
                   11984:                     if ($importedresponses) {
                   11985:                         $metaentry{':responseorder'}.=','.$origid;
                   11986:                     }
                   11987:                 }
                   11988:             }
                   11989:             if ($importedparts) {
                   11990:                 $metaentry{':partorder'}=~s/^\,//;
                   11991:             }
                   11992:             if ($importedresponses) {
                   11993:                 $metaentry{':responseorder'}=~s/^\,//;
                   11994:             }
1.1070    www      11995:         }
                   11996: 
1.737     albertel 11997: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11998: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11999: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12000: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12001: # this is the end of "was not already recently cached
1.71      www      12002:     }
1.599     albertel 12003:     return $metaentry{':'.$what};
1.261     albertel 12004: }
                   12005: 
1.488     albertel 12006: sub metadata_create_package_def {
1.483     albertel 12007:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12008:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12009:     if ($subp eq 'default') { next; }
                   12010:     
1.599     albertel 12011:     if (defined($metaentry{':packages'})) {
                   12012: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12013:     } else {
1.599     albertel 12014: 	$metaentry{':packages'}=$package;
1.483     albertel 12015:     }
                   12016:     my $value=$packagetab{$key};
                   12017:     my $unikey;
                   12018:     $unikey='parameter_0_'.$name;
1.599     albertel 12019:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12020:     $$metathesekeys{$unikey}=1;
1.599     albertel 12021:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12022: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12023:     }
1.599     albertel 12024:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12025: 	$metaentry{':'.$unikey}=
                   12026: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12027:     }
                   12028: }
                   12029: 
1.261     albertel 12030: sub metadata_generate_part0 {
                   12031:     my ($metadata,$metacache,$uri) = @_;
                   12032:     my %allnames;
1.737     albertel 12033:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12034: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12035: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12036: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12037: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12038: 	    $allnames{$name}=$part;
                   12039: 	  }
                   12040: 	}
                   12041:     }
                   12042:     foreach my $name (keys(%allnames)) {
                   12043:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12044:       my $key=":parameter_0_$name";
1.261     albertel 12045:       $$metacache{"$key.part"}='0';
                   12046:       $$metacache{"$key.name"}=$name;
1.428     albertel 12047:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12048: 					   $allnames{$name}.'_'.$name.
                   12049: 					   '.type'};
1.428     albertel 12050:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12051: 			     '.display'};
1.644     www      12052:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12053:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12054:       $$metacache{"$key.display"}=$olddis;
                   12055:     }
1.71      www      12056: }
                   12057: 
1.764     albertel 12058: # ------------------------------------------------------ Devalidate title cache
                   12059: 
                   12060: sub devalidate_title_cache {
                   12061:     my ($url)=@_;
                   12062:     if (!$env{'request.course.id'}) { return; }
                   12063:     my $symb=&symbread($url);
                   12064:     if (!$symb) { return; }
                   12065:     my $key=$env{'request.course.id'}."\0".$symb;
                   12066:     &devalidate_cache_new('title',$key);
                   12067: }
                   12068: 
1.1014    droeschl 12069: # ------------------------------------------------- Get the title of a course
                   12070: 
                   12071: sub current_course_title {
                   12072:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12073: }
1.301     www      12074: # ------------------------------------------------- Get the title of a resource
                   12075: 
                   12076: sub gettitle {
                   12077:     my $urlsymb=shift;
                   12078:     my $symb=&symbread($urlsymb);
1.534     albertel 12079:     if ($symb) {
1.620     albertel 12080: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12081: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12082: 	if (defined($cached)) { 
                   12083: 	    return $result;
                   12084: 	}
1.534     albertel 12085: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12086: 	my $title='';
1.907     albertel 12087: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12088: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12089: 	} else {
                   12090: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12091: 		    &GDBM_READER(),0640)) {
                   12092: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12093: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12094: 		untie(%bighash);
                   12095: 	    }
1.534     albertel 12096: 	}
                   12097: 	$title=~s/\&colon\;/\:/gs;
                   12098: 	if ($title) {
1.1159    www      12099: # Remember both $symb and $title for dynamic metadata
                   12100:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12101:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12102: # Cache this title and then return it
1.599     albertel 12103: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12104: 	}
                   12105: 	$urlsymb=$url;
                   12106:     }
                   12107:     my $title=&metadata($urlsymb,'title');
                   12108:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12109:     return $title;
1.301     www      12110: }
1.613     albertel 12111: 
1.614     albertel 12112: sub get_slot {
                   12113:     my ($which,$cnum,$cdom)=@_;
                   12114:     if (!$cnum || !$cdom) {
1.790     albertel 12115: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12116: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12117: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12118:     }
1.703     albertel 12119:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12120:     my %slotinfo;
                   12121:     if (exists($remembered{$key})) {
                   12122: 	$slotinfo{$which} = $remembered{$key};
                   12123:     } else {
                   12124: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12125: 	&Apache::lonhomework::showhash(%slotinfo);
                   12126: 	my ($tmp)=keys(%slotinfo);
                   12127: 	if ($tmp=~/^error:/) { return (); }
                   12128: 	$remembered{$key} = $slotinfo{$which};
                   12129:     }
1.616     albertel 12130:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12131: 	return %{$slotinfo{$which}};
                   12132:     }
                   12133:     return $slotinfo{$which};
1.614     albertel 12134: }
1.1150    raeburn  12135: 
                   12136: sub get_reservable_slots {
                   12137:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12138:     my $now = time;
                   12139:     my $reservable_info;
                   12140:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12141:     if (exists($remembered{$key})) {
                   12142:         $reservable_info = $remembered{$key};
                   12143:     } else {
                   12144:         my %resv;
                   12145:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12146:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12147:         $reservable_info = \%resv;
                   12148:         $remembered{$key} = $reservable_info;
                   12149:     }
                   12150:     return $reservable_info;
                   12151: }
                   12152: 
                   12153: sub get_course_slots {
                   12154:     my ($cnum,$cdom) = @_;
                   12155:     my $hashid=$cnum.':'.$cdom;
                   12156:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12157:     if (defined($cached)) {
                   12158:         if (ref($result) eq 'HASH') {
                   12159:             return %{$result};
                   12160:         }
                   12161:     } else {
                   12162:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12163:         my ($tmp) = keys(%slots);
                   12164:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12165:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12166:             return %slots;
                   12167:         }
                   12168:     }
                   12169:     return;
                   12170: }
                   12171: 
                   12172: sub devalidate_slots_cache {
                   12173:     my ($cnum,$cdom)=@_;
                   12174:     my $hashid=$cnum.':'.$cdom;
                   12175:     &devalidate_cache_new('allslots',$hashid);
                   12176: }
                   12177: 
1.1172.2.8  raeburn  12178: sub get_coursechange {
                   12179:     my ($cdom,$cnum) = @_;
                   12180:     if ($cdom eq '' || $cnum eq '') {
                   12181:         return unless ($env{'request.course.id'});
                   12182:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12183:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12184:     }
                   12185:     my $hashid=$cdom.'_'.$cnum;
                   12186:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12187:     if ((defined($cached)) && ($change ne '')) {
                   12188:         return $change;
                   12189:     } else {
                   12190:         my %crshash;
                   12191:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12192:         if ($crshash{'internal.contentchange'} eq '') {
                   12193:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12194:             if ($change eq '') {
                   12195:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12196:                 $change = $crshash{'internal.created'};
                   12197:             }
                   12198:         } else {
                   12199:             $change = $crshash{'internal.contentchange'};
                   12200:         }
                   12201:         my $cachetime = 600;
                   12202:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12203:     }
                   12204:     return $change;
                   12205: }
                   12206: 
                   12207: sub devalidate_coursechange_cache {
                   12208:     my ($cnum,$cdom)=@_;
                   12209:     my $hashid=$cnum.':'.$cdom;
                   12210:     &devalidate_cache_new('crschange',$hashid);
                   12211: }
                   12212: 
1.31      www      12213: # ------------------------------------------------- Update symbolic store links
                   12214: 
                   12215: sub symblist {
                   12216:     my ($mapname,%newhash)=@_;
1.438     www      12217:     $mapname=&deversion(&declutter($mapname));
1.31      www      12218:     my %hash;
1.620     albertel 12219:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12220:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12221:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12222: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12223: 		next if ($url eq 'last_known'
                   12224: 			 && $env{'form.no_update_last_known'});
                   12225: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12226: 						    $newhash{$url}->[1],
                   12227: 						    $newhash{$url}->[0]);
1.191     harris41 12228:             }
1.31      www      12229:             if (untie(%hash)) {
                   12230: 		return 'ok';
                   12231:             }
                   12232:         }
                   12233:     }
                   12234:     return 'error';
1.212     www      12235: }
                   12236: 
                   12237: # --------------------------------------------------------------- Verify a symb
                   12238: 
                   12239: sub symbverify {
1.1172.2.11  raeburn  12240:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12241:     my $thisfn=$thisurl;
1.439     www      12242:     $thisfn=&declutter($thisfn);
1.215     www      12243: # direct jump to resource in page or to a sequence - will construct own symbs
                   12244:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12245: # check URL part
1.409     www      12246:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12247: 
1.431     www      12248:     unless ($url eq $thisfn) { return 0; }
1.213     www      12249: 
1.216     www      12250:     $symb=&symbclean($symb);
1.510     www      12251:     $thisurl=&deversion($thisurl);
1.439     www      12252:     $thisfn=&deversion($thisfn);
1.213     www      12253: 
                   12254:     my %bighash;
                   12255:     my $okay=0;
1.431     www      12256: 
1.620     albertel 12257:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12258:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  12259:         my $noclutter;
1.1032    raeburn  12260:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12261:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12262:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12263:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12264:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12265:                 $noclutter = 1;
                   12266:             }
                   12267:         }
                   12268:         my $ids;
                   12269:         if ($noclutter) {
                   12270:             $ids=$bighash{'ids_'.$thisurl};
                   12271:         } else {
                   12272:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12273:         }
1.1102    raeburn  12274:         unless ($ids) {
1.1172.2.13  raeburn  12275:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12276:             $ids=$bighash{$idkey};
1.216     www      12277:         }
                   12278:         if ($ids) {
                   12279: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12280:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12281:                 $symb =~ s/\?.+$//;
                   12282:             }
1.800     albertel 12283: 	    foreach my $id (split(/\,/,$ids)) {
                   12284: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12285:                if (
                   12286:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12287:    eq $symb) {
1.1172.2.11  raeburn  12288:                    if (ref($encstate)) {
                   12289:                        $$encstate = $bighash{'encrypted_'.$id};
                   12290:                    }
1.1172.2.13  raeburn  12291:                    if (($env{'request.role.adv'}) ||
                   12292:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12293:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12294:                        $okay=1;
                   12295:                        last;
                   12296:                    }
                   12297:                }
                   12298:            }
1.216     www      12299:         }
1.213     www      12300: 	untie(%bighash);
                   12301:     }
                   12302:     return $okay;
1.31      www      12303: }
                   12304: 
1.210     www      12305: # --------------------------------------------------------------- Clean-up symb
                   12306: 
                   12307: sub symbclean {
                   12308:     my $symb=shift;
1.568     albertel 12309:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12310: # remove version from map
                   12311:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12312: 
1.210     www      12313: # remove version from URL
                   12314:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12315: 
1.507     www      12316: # remove wrapper
                   12317: 
1.510     www      12318:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12319:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12320:     return $symb;
1.409     www      12321: }
                   12322: 
                   12323: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12324: 
                   12325: sub encode_symb {
                   12326:     my ($map,$resid,$url)=@_;
                   12327:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12328: }
1.409     www      12329: 
                   12330: sub decode_symb {
1.568     albertel 12331:     my $symb=shift;
                   12332:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12333:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12334:     return (&fixversion($map),$resid,&fixversion($url));
                   12335: }
                   12336: 
                   12337: sub fixversion {
                   12338:     my $fn=shift;
1.609     banghart 12339:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12340:     my %bighash;
                   12341:     my $uri=&clutter($fn);
1.620     albertel 12342:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12343: # is this cached?
1.599     albertel 12344:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12345:     if (defined($cached)) { return $result; }
                   12346: # unfortunately not cached, or expired
1.620     albertel 12347:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12348: 	    &GDBM_READER(),0640)) {
                   12349:  	if ($bighash{'version_'.$uri}) {
                   12350:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12351:  	    unless (($version eq 'mostrecent') || 
                   12352: 		    ($version==&getversion($uri))) {
1.440     www      12353:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12354:  	    }
                   12355:  	}
                   12356:  	untie %bighash;
1.413     www      12357:     }
1.599     albertel 12358:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12359: }
                   12360: 
                   12361: sub deversion {
                   12362:     my $url=shift;
                   12363:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12364:     return $url;
1.210     www      12365: }
                   12366: 
1.31      www      12367: # ------------------------------------------------------ Return symb list entry
                   12368: 
                   12369: sub symbread {
1.1172.2.66  raeburn  12370:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12371:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12372:     if (defined($env{$cache_str})) {
                   12373:         if ($ignorecachednull) {
                   12374:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12375:         } else {
                   12376:             return $env{$cache_str};
                   12377:         }
                   12378:     }
1.242     www      12379: # no filename provided? try from environment
1.1172.2.54  raeburn  12380:     unless ($thisfn) {
1.620     albertel 12381:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12382:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12383:         }
                   12384:         $thisfn=$env{'request.filename'};
1.44      www      12385:     }
1.569     albertel 12386:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12387: # is that filename actually a symb? Verify, clean, and return
                   12388:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12389: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12390: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12391: 	}
1.242     www      12392:     }
1.44      www      12393:     $thisfn=declutter($thisfn);
1.31      www      12394:     my %hash;
1.37      www      12395:     my %bighash;
                   12396:     my $syval='';
1.620     albertel 12397:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12398:         my $targetfn = $thisfn;
1.609     banghart 12399:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12400:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12401:         }
1.687     albertel 12402: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12403: 	    $targetfn=$1;
                   12404: 	}
1.620     albertel 12405:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12406:                       &GDBM_READER(),0640)) {
1.481     raeburn  12407: 	    $syval=$hash{$targetfn};
1.37      www      12408:             untie(%hash);
                   12409:         }
                   12410: # ---------------------------------------------------------- There was an entry
                   12411:         if ($syval) {
1.601     albertel 12412: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12413: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12414: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12415: 		    #return $env{$cache_str}='';
1.601     albertel 12416: 		#}    
                   12417: 		#$syval.=$1;
                   12418: 	    #}
1.37      www      12419:         } else {
                   12420: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12421:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12422:                             &GDBM_READER(),0640)) {
1.37      www      12423: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12424:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12425:               unless ($ids) { 
                   12426:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12427:               }
                   12428:               unless ($ids) {
                   12429: # alias?
                   12430: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12431:               }
1.37      www      12432:               if ($ids) {
                   12433: # ------------------------------------------------------------------- Has ID(s)
                   12434:                  my @possibilities=split(/\,/,$ids);
1.39      www      12435:                  if ($#possibilities==0) {
                   12436: # ----------------------------------------------- There is only one possibility
1.37      www      12437: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12438: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12439: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12440:                      if (ref($possibles) eq 'HASH') {
                   12441:                          $possibles->{$syval} = 1;
                   12442:                      }
                   12443:                      if ($checkforblock) {
                   12444:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12445:                          if (@blockers) {
                   12446:                              $syval = '';
                   12447:                              return;
                   12448:                          }
                   12449:                      }
                   12450:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12451: # ------------------------------------------ There is more than one possibility
                   12452:                      my $realpossible=0;
1.800     albertel 12453:                      foreach my $id (@possibilities) {
                   12454: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12455:                          my $canaccess;
                   12456:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12457:                              $canaccess = 1;
                   12458:                          } else {
                   12459:                              $canaccess = &allowed('bre',$file);
                   12460:                          }
                   12461:                          if ($canaccess) {
                   12462:          		     my ($mapid,$resid)=split(/\./,$id);
                   12463:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12464:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12465:                                                              $resid,$thisfn);
                   12466:                                  if (ref($possibles) eq 'HASH') {
                   12467:                                      $possibles->{$syval} = 1;
                   12468:                                  }
                   12469:                                  if ($checkforblock) {
                   12470:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12471:                                      unless (@blockers > 0) {
                   12472:                                          $syval = $poss_syval;
                   12473:                                          $realpossible++;
                   12474:                                      }
                   12475:                                  } else {
                   12476:                                      $syval = $poss_syval;
                   12477:                                      $realpossible++;
                   12478:                                  }
                   12479:                              }
1.39      www      12480: 			 }
1.191     harris41 12481:                      }
1.39      www      12482: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12483:                  } else {
                   12484:                      $syval='';
1.37      www      12485:                  }
                   12486: 	      }
1.1172.2.66  raeburn  12487:               untie(%bighash);
1.481     raeburn  12488:            }
1.31      www      12489:         }
1.62      www      12490:         if ($syval) {
1.620     albertel 12491: 	    return $env{$cache_str}=$syval;
1.62      www      12492:         }
1.31      www      12493:     }
1.949     raeburn  12494:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12495:     return $env{$cache_str}='';
1.31      www      12496: }
                   12497: 
                   12498: # ---------------------------------------------------------- Return random seed
                   12499: 
1.32      www      12500: sub numval {
                   12501:     my $txt=shift;
                   12502:     $txt=~tr/A-J/0-9/;
                   12503:     $txt=~tr/a-j/0-9/;
                   12504:     $txt=~tr/K-T/0-9/;
                   12505:     $txt=~tr/k-t/0-9/;
                   12506:     $txt=~tr/U-Z/0-5/;
                   12507:     $txt=~tr/u-z/0-5/;
                   12508:     $txt=~s/\D//g;
1.564     albertel 12509:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12510:     return int($txt);
1.368     albertel 12511: }
                   12512: 
1.484     albertel 12513: sub numval2 {
                   12514:     my $txt=shift;
                   12515:     $txt=~tr/A-J/0-9/;
                   12516:     $txt=~tr/a-j/0-9/;
                   12517:     $txt=~tr/K-T/0-9/;
                   12518:     $txt=~tr/k-t/0-9/;
                   12519:     $txt=~tr/U-Z/0-5/;
                   12520:     $txt=~tr/u-z/0-5/;
                   12521:     $txt=~s/\D//g;
                   12522:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12523:     my $total;
                   12524:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12525:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12526:     return int($total);
                   12527: }
                   12528: 
1.575     albertel 12529: sub numval3 {
                   12530:     use integer;
                   12531:     my $txt=shift;
                   12532:     $txt=~tr/A-J/0-9/;
                   12533:     $txt=~tr/a-j/0-9/;
                   12534:     $txt=~tr/K-T/0-9/;
                   12535:     $txt=~tr/k-t/0-9/;
                   12536:     $txt=~tr/U-Z/0-5/;
                   12537:     $txt=~tr/u-z/0-5/;
                   12538:     $txt=~s/\D//g;
                   12539:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12540:     my $total;
                   12541:     foreach my $val (@txts) { $total+=$val; }
                   12542:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12543:     return $total;
                   12544: }
                   12545: 
1.675     albertel 12546: sub digest {
                   12547:     my ($data)=@_;
                   12548:     my $digest=&Digest::MD5::md5($data);
                   12549:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12550:     my ($e,$f);
                   12551:     {
                   12552:         use integer;
                   12553:         $e=($a+$b);
                   12554:         $f=($c+$d);
                   12555:         if ($_64bit) {
                   12556:             $e=(($e<<32)>>32);
                   12557:             $f=(($f<<32)>>32);
                   12558:         }
                   12559:     }
                   12560:     if (wantarray) {
                   12561: 	return ($e,$f);
                   12562:     } else {
                   12563: 	my $g;
                   12564: 	{
                   12565: 	    use integer;
                   12566: 	    $g=($e+$f);
                   12567: 	    if ($_64bit) {
                   12568: 		$g=(($g<<32)>>32);
                   12569: 	    }
                   12570: 	}
                   12571: 	return $g;
                   12572:     }
                   12573: }
                   12574: 
1.368     albertel 12575: sub latest_rnd_algorithm_id {
1.675     albertel 12576:     return '64bit5';
1.366     albertel 12577: }
1.32      www      12578: 
1.503     albertel 12579: sub get_rand_alg {
                   12580:     my ($courseid)=@_;
1.790     albertel 12581:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12582:     if ($courseid) {
1.620     albertel 12583: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12584:     }
                   12585:     return &latest_rnd_algorithm_id();
                   12586: }
                   12587: 
1.562     albertel 12588: sub validCODE {
                   12589:     my ($CODE)=@_;
                   12590:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12591:     return 0;
                   12592: }
                   12593: 
1.491     albertel 12594: sub getCODE {
1.620     albertel 12595:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12596:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12597: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12598: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12599: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12600:     }
                   12601:     return undef;
                   12602: }
1.1133    foxr     12603: #
                   12604: #  Determines the random seed for a specific context:
                   12605: #
                   12606: # parameters:
                   12607: #   symb      - in course context the symb for the seed.
                   12608: #   course_id - The course id of the form domain_coursenum.
                   12609: #   domain    - Domain for the user.
                   12610: #   course    - Course for the user.
                   12611: #   cenv      - environment of the course.
                   12612: #
                   12613: # NOTE:
                   12614: #   All parameters are picked out of the environment if missing
                   12615: #   or not defined.
                   12616: #   If a symb cannot be determined the current time is used instead.
                   12617: #
                   12618: #  For a given well defined symb, courside, domain, username,
                   12619: #  and course environment, the seed is reproducible.
                   12620: #
1.31      www      12621: sub rndseed {
1.1133    foxr     12622:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12623:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12624:     if (!defined($symb)) {
1.366     albertel 12625: 	unless ($symb=$wsymb) { return time; }
                   12626:     }
1.1146    foxr     12627:     if (!defined $courseid) { 
                   12628: 	$courseid=$wcourseid; 
                   12629:     }
                   12630:     if (!defined $domain) { $domain=$wdomain; }
                   12631:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12632: 
                   12633:     my $which;
                   12634:     if (defined($cenv->{'rndseed'})) {
                   12635: 	$which = $cenv->{'rndseed'};
                   12636:     } else {
                   12637: 	$which =&get_rand_alg($courseid);
                   12638:     }
1.491     albertel 12639:     if (defined(&getCODE())) {
1.675     albertel 12640: 	if ($which eq '64bit5') {
                   12641: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12642: 	} elsif ($which eq '64bit4') {
1.575     albertel 12643: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12644: 	} else {
                   12645: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12646: 	}
1.675     albertel 12647:     } elsif ($which eq '64bit5') {
                   12648: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12649:     } elsif ($which eq '64bit4') {
                   12650: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12651:     } elsif ($which eq '64bit3') {
                   12652: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12653:     } elsif ($which eq '64bit2') {
                   12654: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12655:     } elsif ($which eq '64bit') {
                   12656: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12657:     }
                   12658:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12659: }
                   12660: 
                   12661: sub rndseed_32bit {
                   12662:     my ($symb,$courseid,$domain,$username)=@_;
                   12663:     {
                   12664: 	use integer;
                   12665: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12666: 	my $symbseed=numval($symb) << 22;
                   12667: 	my $namechck=unpack("%32C*",$username) << 17;
                   12668: 	my $nameseed=numval($username) << 12;
                   12669: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12670: 	my $courseseed=unpack("%32C*",$courseid);
                   12671: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12672: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12673: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12674: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12675: 	return $num;
                   12676:     }
                   12677: }
                   12678: 
                   12679: sub rndseed_64bit {
                   12680:     my ($symb,$courseid,$domain,$username)=@_;
                   12681:     {
                   12682: 	use integer;
                   12683: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12684: 	my $symbseed=numval($symb) << 10;
                   12685: 	my $namechck=unpack("%32S*",$username);
                   12686: 	
                   12687: 	my $nameseed=numval($username) << 21;
                   12688: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12689: 	my $courseseed=unpack("%32S*",$courseid);
                   12690: 	
                   12691: 	my $num1=$symbchck+$symbseed+$namechck;
                   12692: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12693: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12694: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12695: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12696: 	return "$num1,$num2";
1.155     albertel 12697:     }
1.366     albertel 12698: }
                   12699: 
1.443     albertel 12700: sub rndseed_64bit2 {
                   12701:     my ($symb,$courseid,$domain,$username)=@_;
                   12702:     {
                   12703: 	use integer;
                   12704: 	# strings need to be an even # of cahracters long, it it is odd the
                   12705:         # last characters gets thrown away
                   12706: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12707: 	my $symbseed=numval($symb) << 10;
                   12708: 	my $namechck=unpack("%32S*",$username.' ');
                   12709: 	
                   12710: 	my $nameseed=numval($username) << 21;
1.501     albertel 12711: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12712: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12713: 	
                   12714: 	my $num1=$symbchck+$symbseed+$namechck;
                   12715: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12716: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12717: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12718: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12719: 	return "$num1,$num2";
                   12720:     }
                   12721: }
                   12722: 
                   12723: sub rndseed_64bit3 {
                   12724:     my ($symb,$courseid,$domain,$username)=@_;
                   12725:     {
                   12726: 	use integer;
                   12727: 	# strings need to be an even # of cahracters long, it it is odd the
                   12728:         # last characters gets thrown away
                   12729: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12730: 	my $symbseed=numval2($symb) << 10;
                   12731: 	my $namechck=unpack("%32S*",$username.' ');
                   12732: 	
                   12733: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12734: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12735: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12736: 	
                   12737: 	my $num1=$symbchck+$symbseed+$namechck;
                   12738: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12739: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12740: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12741: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12742: 	
1.503     albertel 12743: 	return "$num1:$num2";
1.443     albertel 12744:     }
                   12745: }
                   12746: 
1.575     albertel 12747: sub rndseed_64bit4 {
                   12748:     my ($symb,$courseid,$domain,$username)=@_;
                   12749:     {
                   12750: 	use integer;
                   12751: 	# strings need to be an even # of cahracters long, it it is odd the
                   12752:         # last characters gets thrown away
                   12753: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12754: 	my $symbseed=numval3($symb) << 10;
                   12755: 	my $namechck=unpack("%32S*",$username.' ');
                   12756: 	
                   12757: 	my $nameseed=numval3($username) << 21;
                   12758: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12759: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12760: 	
                   12761: 	my $num1=$symbchck+$symbseed+$namechck;
                   12762: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12763: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12764: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12765: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12766: 	
1.575     albertel 12767: 	return "$num1:$num2";
                   12768:     }
                   12769: }
                   12770: 
1.675     albertel 12771: sub rndseed_64bit5 {
                   12772:     my ($symb,$courseid,$domain,$username)=@_;
                   12773:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12774:     return "$num1:$num2";
                   12775: }
                   12776: 
1.366     albertel 12777: sub rndseed_CODE_64bit {
                   12778:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12779:     {
1.366     albertel 12780: 	use integer;
1.443     albertel 12781: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12782: 	my $symbseed=numval2($symb);
1.491     albertel 12783: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12784: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12785: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12786: 	my $num1=$symbseed+$CODEchck;
                   12787: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12788: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12789: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12790: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12791: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12792: 	return "$num1:$num2";
1.366     albertel 12793:     }
                   12794: }
                   12795: 
1.575     albertel 12796: sub rndseed_CODE_64bit4 {
                   12797:     my ($symb,$courseid,$domain,$username)=@_;
                   12798:     {
                   12799: 	use integer;
                   12800: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12801: 	my $symbseed=numval3($symb);
                   12802: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12803: 	my $CODEseed=numval3(&getCODE());
                   12804: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12805: 	my $num1=$symbseed+$CODEchck;
                   12806: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12807: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12808: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12809: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12810: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12811: 	return "$num1:$num2";
                   12812:     }
                   12813: }
                   12814: 
1.675     albertel 12815: sub rndseed_CODE_64bit5 {
                   12816:     my ($symb,$courseid,$domain,$username)=@_;
                   12817:     my $code = &getCODE();
                   12818:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12819:     return "$num1:$num2";
                   12820: }
                   12821: 
1.366     albertel 12822: sub setup_random_from_rndseed {
                   12823:     my ($rndseed)=@_;
1.503     albertel 12824:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12825: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12826:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12827:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12828:         } else {
                   12829:             &Math::Random::random_set_seed($num1,$num2);
                   12830:         }
1.366     albertel 12831:     } else {
                   12832: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12833:     }
1.36      albertel 12834: }
                   12835: 
1.474     albertel 12836: sub latest_receipt_algorithm_id {
1.835     albertel 12837:     return 'receipt3';
1.474     albertel 12838: }
                   12839: 
1.480     www      12840: sub recunique {
                   12841:     my $fucourseid=shift;
                   12842:     my $unique;
1.835     albertel 12843:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12844: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12845: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12846:     } else {
                   12847: 	$unique=$perlvar{'lonReceipt'};
                   12848:     }
                   12849:     return unpack("%32C*",$unique);
                   12850: }
                   12851: 
                   12852: sub recprefix {
                   12853:     my $fucourseid=shift;
                   12854:     my $prefix;
1.835     albertel 12855:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12856: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12857: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12858:     } else {
                   12859: 	$prefix=$perlvar{'lonHostID'};
                   12860:     }
                   12861:     return unpack("%32C*",$prefix);
                   12862: }
                   12863: 
1.76      www      12864: sub ireceipt {
1.474     albertel 12865:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12866: 
                   12867:     my $return =&recprefix($fucourseid).'-';
                   12868: 
                   12869:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12870: 	$env{'request.state'} eq 'construct') {
                   12871: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12872: 	return $return;
                   12873:     }
                   12874: 
1.76      www      12875:     my $cuname=unpack("%32C*",$funame);
                   12876:     my $cudom=unpack("%32C*",$fudom);
                   12877:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12878:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12879:     my $cunique=&recunique($fucourseid);
1.474     albertel 12880:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12881:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12882: 
1.790     albertel 12883: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12884: 			       
                   12885: 	$return.= ($cunique%$cuname+
                   12886: 		   $cunique%$cudom+
                   12887: 		   $cusymb%$cuname+
                   12888: 		   $cusymb%$cudom+
                   12889: 		   $cucourseid%$cuname+
                   12890: 		   $cucourseid%$cudom+
                   12891: 		   $cpart%$cuname+
                   12892: 		   $cpart%$cudom);
                   12893:     } else {
                   12894: 	$return.= ($cunique%$cuname+
                   12895: 		   $cunique%$cudom+
                   12896: 		   $cusymb%$cuname+
                   12897: 		   $cusymb%$cudom+
                   12898: 		   $cucourseid%$cuname+
                   12899: 		   $cucourseid%$cudom);
                   12900:     }
                   12901:     return $return;
1.76      www      12902: }
                   12903: 
                   12904: sub receipt {
1.474     albertel 12905:     my ($part)=@_;
1.790     albertel 12906:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12907:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12908: }
1.260     ng       12909: 
1.790     albertel 12910: sub whichuser {
                   12911:     my ($passedsymb)=@_;
                   12912:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12913:     if (defined($env{'form.grade_symb'})) {
                   12914: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12915: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12916: 	if (!$allowed &&
                   12917: 	    exists($env{'request.course.sec'}) &&
                   12918: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12919: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12920: 			      '/'.$env{'request.course.sec'});
                   12921: 	}
                   12922: 	if ($allowed) {
                   12923: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12924: 	    $courseid=$tmp_courseid;
                   12925: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12926: 	    ($name)=&get_env_multiple('form.grade_username');
                   12927: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12928: 	}
                   12929:     }
                   12930:     if (!$passedsymb) {
                   12931: 	$symb=&symbread();
                   12932:     } else {
                   12933: 	$symb=$passedsymb;
                   12934:     }
                   12935:     $courseid=$env{'request.course.id'};
                   12936:     $domain=$env{'user.domain'};
                   12937:     $name=$env{'user.name'};
                   12938:     if ($name eq 'public' && $domain eq 'public') {
                   12939: 	if (!defined($env{'form.username'})) {
                   12940: 	    $env{'form.username'}.=time.rand(10000000);
                   12941: 	}
                   12942: 	$name.=$env{'form.username'};
                   12943:     }
                   12944:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12945: 
                   12946: }
                   12947: 
1.36      albertel 12948: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12949: # returns either the contents of the file or 
                   12950: # -1 if the file doesn't exist
1.481     raeburn  12951: #
                   12952: # if the target is a file that was uploaded via DOCS, 
                   12953: # a check will be made to see if a current copy exists on the local server,
                   12954: # if it does this will be served, otherwise a copy will be retrieved from
                   12955: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12956: # the local server.   
1.472     albertel 12957: 
1.36      albertel 12958: sub getfile {
1.538     albertel 12959:     my ($file) = @_;
1.609     banghart 12960:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12961:     &repcopy($file);
                   12962:     return &readfile($file);
                   12963: }
                   12964: 
                   12965: sub repcopy_userfile {
                   12966:     my ($file)=@_;
1.1142    raeburn  12967:     my $londocroot = $perlvar{'lonDocRoot'};
                   12968:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12969:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12970:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12971: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12972:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12973:     if (-e "$file") {
1.828     www      12974: # we already have a local copy, check it out
1.538     albertel 12975: 	my @fileinfo = stat($file);
1.828     www      12976: 	my $rtncode;
                   12977: 	my $info;
1.538     albertel 12978: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12979: 	if ($lwpresp ne 'ok') {
1.828     www      12980: # there is no such file anymore, even though we had a local copy
1.482     albertel 12981: 	    if ($rtncode eq '404') {
1.538     albertel 12982: 		unlink($file);
1.482     albertel 12983: 	    }
                   12984: 	    return -1;
                   12985: 	}
                   12986: 	if ($info < $fileinfo[9]) {
1.828     www      12987: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12988: 	    return 'ok';
1.828     www      12989: 	} else {
                   12990: # the file is outdated, get rid of it
                   12991: 	    unlink($file);
1.482     albertel 12992: 	}
1.828     www      12993:     }
                   12994: # one way or the other, at this point, we don't have the file
                   12995: # construct the correct path for the file
                   12996:     my @parts = ($cdom,$cnum); 
                   12997:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12998: 	push @parts, split(/\//,$1);
                   12999:     }
                   13000:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13001:     foreach my $part (@parts) {
                   13002: 	$path .= '/'.$part;
                   13003: 	if (!-e $path) {
                   13004: 	    mkdir($path,0770);
1.482     albertel 13005: 	}
                   13006:     }
1.828     www      13007: # now the path exists for sure
                   13008: # get a user agent
                   13009:     my $ua=new LWP::UserAgent;
                   13010:     my $transferfile=$file.'.in.transfer';
                   13011: # FIXME: this should flock
                   13012:     if (-e $transferfile) { return 'ok'; }
                   13013:     my $request;
                   13014:     $uri=~s/^\///;
1.980     raeburn  13015:     my $homeserver = &homeserver($cnum,$cdom);
                   13016:     my $protocol = $protocol{$homeserver};
                   13017:     $protocol = 'http' if ($protocol ne 'https');
                   13018:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      13019:     my $response=$ua->request($request,$transferfile);
                   13020: # did it work?
                   13021:     if ($response->is_error()) {
                   13022: 	unlink($transferfile);
                   13023: 	&logthis("Userfile repcopy failed for $uri");
                   13024: 	return -1;
                   13025:     }
                   13026: # worked, rename the transfer file
                   13027:     rename($transferfile,$file);
1.607     raeburn  13028:     return 'ok';
1.481     raeburn  13029: }
                   13030: 
1.517     albertel 13031: sub tokenwrapper {
                   13032:     my $uri=shift;
1.980     raeburn  13033:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13034:     $uri=~s|^/||;
1.620     albertel 13035:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13036:     my $token=$1;
1.552     albertel 13037:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13038:     if ($udom && $uname && $file) {
                   13039: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13040:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13041:         my $homeserver = &homeserver($uname,$udom);
                   13042:         my $protocol = $protocol{$homeserver};
                   13043:         $protocol = 'http' if ($protocol ne 'https');
                   13044:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13045:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13046:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13047:     } else {
                   13048:         return '/adm/notfound.html';
                   13049:     }
                   13050: }
                   13051: 
1.828     www      13052: # call with reqtype HEAD: get last modification time
                   13053: # call with reqtype GET: get the file contents
                   13054: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13055: #
1.481     raeburn  13056: sub getuploaded {
                   13057:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13058:     $uri=~s/^\///;
1.980     raeburn  13059:     my $homeserver = &homeserver($cnum,$cdom);
                   13060:     my $protocol = $protocol{$homeserver};
                   13061:     $protocol = 'http' if ($protocol ne 'https');
                   13062:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13063:     my $ua=new LWP::UserAgent;
                   13064:     my $request=new HTTP::Request($reqtype,$uri);
                   13065:     my $response=$ua->request($request);
                   13066:     $$rtncode = $response->code;
1.482     albertel 13067:     if (! $response->is_success()) {
                   13068: 	return 'failed';
                   13069:     }      
                   13070:     if ($reqtype eq 'HEAD') {
1.486     www      13071: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13072:     } elsif ($reqtype eq 'GET') {
                   13073: 	$$info = $response->content;
1.472     albertel 13074:     }
1.482     albertel 13075:     return 'ok';
1.36      albertel 13076: }
                   13077: 
1.481     raeburn  13078: sub readfile {
                   13079:     my $file = shift;
                   13080:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13081:     my $fh;
1.1172.2.96  raeburn  13082:     open($fh,"<",$file);
1.481     raeburn  13083:     my $a='';
1.800     albertel 13084:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13085:     return $a;
                   13086: }
                   13087: 
1.36      albertel 13088: sub filelocation {
1.590     banghart 13089:     my ($dir,$file) = @_;
                   13090:     my $location;
                   13091:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13092: 
                   13093:     if ($file =~ m-^/adm/-) {
                   13094: 	$file=~s-^/adm/wrapper/-/-;
                   13095: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13096:     }
1.882     albertel 13097: 
1.1139    www      13098:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13099:         $location = $file;
1.609     banghart 13100:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13101:         my ($udom,$uname,$filename)=
1.811     albertel 13102:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13103:         my $home=&homeserver($uname,$udom);
                   13104:         my $is_me=0;
                   13105:         my @ids=&current_machine_ids();
                   13106:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13107:         if ($is_me) {
1.1117    foxr     13108:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13109:         } else {
                   13110:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13111:   	      $udom.'/'.$uname.'/'.$filename;
                   13112:         }
1.882     albertel 13113:     } elsif ($file =~ m-^/adm/-) {
                   13114: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13115:     } else {
                   13116:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13117:         $file=~s:^/(res|priv)/:/:;
                   13118:         my $space=$1;
1.590     banghart 13119:         if ( !( $file =~ m:^/:) ) {
                   13120:             $location = $dir. '/'.$file;
                   13121:         } else {
1.1142    raeburn  13122:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13123:         }
1.59      albertel 13124:     }
1.590     banghart 13125:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13126:     while ($location=~m{/\.\./}) {
                   13127: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13128: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13129: 	} else {
                   13130: 	    $location=~ s{/\.\./}{/}g;
                   13131: 	}
                   13132:     } #remove dir/..
1.590     banghart 13133:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13134:     return $location;
1.46      www      13135: }
1.36      albertel 13136: 
1.46      www      13137: sub hreflocation {
                   13138:     my ($dir,$file)=@_;
1.980     raeburn  13139:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13140: 	$file=filelocation($dir,$file);
1.700     albertel 13141:     } elsif ($file=~m-^/adm/-) {
                   13142: 	$file=~s-^/adm/wrapper/-/-;
                   13143: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13144:     }
                   13145:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13146: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13147:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13148: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13149: 	        {/uploaded/$1/$2/}x;
1.46      www      13150:     }
1.913     albertel 13151:     if ($file=~ m{^/userfiles/}) {
                   13152: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13153:     }
1.462     albertel 13154:     return $file;
1.465     albertel 13155: }
                   13156: 
1.1139    www      13157: 
                   13158: 
                   13159: 
                   13160: 
1.465     albertel 13161: sub current_machine_domains {
1.853     albertel 13162:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13163: }
                   13164: 
                   13165: sub machine_domains {
                   13166:     my ($hostname) = @_;
1.465     albertel 13167:     my @domains;
1.838     albertel 13168:     my %hostname = &all_hostnames();
1.465     albertel 13169:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13170: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13171: 	if ($hostname eq $name) {
1.844     albertel 13172: 	    push(@domains,&host_domain($id));
1.465     albertel 13173: 	}
                   13174:     }
                   13175:     return @domains;
                   13176: }
                   13177: 
                   13178: sub current_machine_ids {
1.853     albertel 13179:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13180: }
                   13181: 
                   13182: sub machine_ids {
                   13183:     my ($hostname) = @_;
                   13184:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13185:     my @ids;
1.888     albertel 13186:     my %name_to_host = &all_names();
1.889     albertel 13187:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13188: 	return @{ $name_to_host{$hostname} };
                   13189:     }
                   13190:     return;
1.31      www      13191: }
                   13192: 
1.824     raeburn  13193: sub additional_machine_domains {
                   13194:     my @domains;
1.1172.2.96  raeburn  13195:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13196:     while( my $line = <$fh>) {
                   13197:         $line =~ s/\s//g;
                   13198:         push(@domains,$line);
                   13199:     }
                   13200:     return @domains;
                   13201: }
                   13202: 
                   13203: sub default_login_domain {
                   13204:     my $domain = $perlvar{'lonDefDomain'};
                   13205:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13206:     foreach my $posdom (&current_machine_domains(),
                   13207:                         &additional_machine_domains()) {
                   13208:         if (lc($posdom) eq lc($testdomain)) {
                   13209:             $domain=$posdom;
                   13210:             last;
                   13211:         }
                   13212:     }
                   13213:     return $domain;
                   13214: }
                   13215: 
1.1172.2.106  raeburn  13216: sub shared_institution {
                   13217:     my ($dom) = @_;
                   13218:     my $same_intdom;
                   13219:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13220:     if ($hostintdom ne '') {
                   13221:         my %iphost = &get_iphost();
                   13222:         my $primary_id = &domain($dom,'primary');
                   13223:         my $primary_ip = &get_host_ip($primary_id);
                   13224:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13225:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13226:                 my $intdom = &internet_dom($id);
                   13227:                 if ($intdom eq $hostintdom) {
                   13228:                     $same_intdom = 1;
                   13229:                     last;
                   13230:                 }
                   13231:             }
                   13232:         }
                   13233:     }
                   13234:     return $same_intdom;
                   13235: }
                   13236: 
1.31      www      13237: # ------------------------------------------------------------- Declutters URLs
                   13238: 
                   13239: sub declutter {
                   13240:     my $thisfn=shift;
1.569     albertel 13241:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13242:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13243:         $thisfn=~s{^/home/httpd/html}{};
                   13244:     }
1.31      www      13245:     $thisfn=~s/^\///;
1.697     albertel 13246:     $thisfn=~s|^adm/wrapper/||;
                   13247:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13248:     $thisfn=~s/^res\///;
1.1172    bisitz   13249:     $thisfn=~s/^priv\///;
1.1032    raeburn  13250:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13251:         $thisfn=~s/\?.+$//;
                   13252:     }
1.268     www      13253:     return $thisfn;
                   13254: }
                   13255: 
                   13256: # ------------------------------------------------------------- Clutter up URLs
                   13257: 
                   13258: sub clutter {
                   13259:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13260:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13261: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13262:        $thisfn='/res'.$thisfn; 
                   13263:     }
1.1031    raeburn  13264:     if ($thisfn !~m|^/adm|) {
                   13265: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13266: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13267: 	} else {
                   13268: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13269: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13270: 	    if ($embstyle eq 'ssi'
                   13271: 		|| ($embstyle eq 'hdn')
                   13272: 		|| ($embstyle eq 'rat')
                   13273: 		|| ($embstyle eq 'prv')
                   13274: 		|| ($embstyle eq 'ign')) {
                   13275: 		#do nothing with these
                   13276: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13277: 		|| ($embstyle eq 'emb')
                   13278: 		|| ($embstyle eq 'wrp')) {
                   13279: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13280: 	    } elsif ($embstyle eq 'unk'
                   13281: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13282: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13283: 	    } else {
1.718     www      13284: #		&logthis("Got a blank emb style");
1.695     albertel 13285: 	    }
1.694     albertel 13286: 	}
                   13287:     }
1.31      www      13288:     return $thisfn;
1.12      www      13289: }
                   13290: 
1.787     albertel 13291: sub clutter_with_no_wrapper {
                   13292:     my $uri = &clutter(shift);
                   13293:     if ($uri =~ m-^/adm/-) {
                   13294: 	$uri =~ s-^/adm/wrapper/-/-;
                   13295: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13296:     }
                   13297:     return $uri;
                   13298: }
                   13299: 
1.557     albertel 13300: sub freeze_escape {
                   13301:     my ($value)=@_;
                   13302:     if (ref($value)) {
                   13303: 	$value=&nfreeze($value);
                   13304: 	return '__FROZEN__'.&escape($value);
                   13305:     }
                   13306:     return &escape($value);
                   13307: }
                   13308: 
1.11      www      13309: 
1.557     albertel 13310: sub thaw_unescape {
                   13311:     my ($value)=@_;
                   13312:     if ($value =~ /^__FROZEN__/) {
                   13313: 	substr($value,0,10,undef);
                   13314: 	$value=&unescape($value);
                   13315: 	return &thaw($value);
                   13316:     }
                   13317:     return &unescape($value);
                   13318: }
                   13319: 
1.436     albertel 13320: sub correct_line_ends {
                   13321:     my ($result)=@_;
                   13322:     $$result =~s/\r\n/\n/mg;
                   13323:     $$result =~s/\r/\n/mg;
1.415     albertel 13324: }
1.1       albertel 13325: # ================================================================ Main Program
                   13326: 
1.184     www      13327: sub goodbye {
1.204     albertel 13328:    &logthis("Starting Shut down");
1.443     albertel 13329: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13330:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13331: #converted
1.599     albertel 13332: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13333:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13334: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13335: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13336: #1.1 only
1.870     albertel 13337: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13338: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13339: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13340: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13341:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13342:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13343:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13344:    &flushcourselogs();
                   13345:    &logthis("Shutting down");
                   13346: }
                   13347: 
1.852     albertel 13348: sub get_dns {
1.1172.2.17  raeburn  13349:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13350:     if (!$ignore_cache) {
                   13351: 	my ($content,$cached)=
                   13352: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13353: 	if ($cached) {
1.1172.2.17  raeburn  13354: 	    &$func($content,$hashref);
1.869     albertel 13355: 	    return;
                   13356: 	}
                   13357:     }
                   13358: 
                   13359:     my %alldns;
1.1172.2.96  raeburn  13360:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13361:         foreach my $dns (<$config>) {
                   13362: 	    next if ($dns !~ /^\^(\S*)/x);
                   13363:             my $line = $1;
                   13364:             my ($host,$protocol) = split(/:/,$line);
                   13365:             if ($protocol ne 'https') {
                   13366:                 $protocol = 'http';
                   13367:             }
                   13368: 	    $alldns{$host} = $protocol;
1.979     raeburn  13369:         }
1.1172.2.96  raeburn  13370:         close($config);
1.869     albertel 13371:     }
                   13372:     while (%alldns) {
1.1172.2.52  raeburn  13373: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13374: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13375:         $ua->timeout(30);
1.979     raeburn  13376: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13377: 	my $response=$ua->request($request);
1.979     raeburn  13378:         delete($alldns{$dns});
1.852     albertel 13379: 	next if ($response->is_error());
                   13380: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13381:         unless ($nocache) {
1.1172.2.23  raeburn  13382: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13383:         }
                   13384: 	&$func(\@content,$hashref);
1.869     albertel 13385: 	return;
1.852     albertel 13386:     }
1.871     albertel 13387:     my $which = (split('/',$url))[3];
                   13388:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13389:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13390:         my @content = <$config>;
                   13391:         &$func(\@content,$hashref);
                   13392:     }
1.1172.2.17  raeburn  13393:     return;
                   13394: }
                   13395: 
                   13396: # ------------------------------------------------------Get DNS checksums file
                   13397: sub parse_dns_checksums_tab {
                   13398:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13399:     my $lonhost = $perlvar{'lonHostID'};
                   13400:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13401:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13402:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13403:     my $webconfdir = '/etc/httpd/conf';
                   13404:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13405:         $webconfdir = '/etc/apache2';
                   13406:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13407:         if ($1 >= 10) {
                   13408:             $webconfdir = '/etc/apache2';
                   13409:         }
                   13410:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13411:         if ($1 >= 10.0) {
                   13412:             $webconfdir = '/etc/apache2';
                   13413:         }
                   13414:     }
1.1172.2.17  raeburn  13415:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13416:     my (%chksum,%revnum);
                   13417:     if (ref($lines) eq 'ARRAY') {
                   13418:         chomp(@{$lines});
1.1172.2.34  raeburn  13419:         my $version = shift(@{$lines});
                   13420:         if ($version eq $release) {
1.1172.2.17  raeburn  13421:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13422:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13423:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13424:                     if ($webconfdir eq '/etc/apache2') {
                   13425:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13426:                     }
                   13427:                 }
1.1172.2.34  raeburn  13428:                 $chksum{$file} = $shasum;
                   13429:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13430:             }
                   13431:             if (ref($hashref) eq 'HASH') {
                   13432:                 %{$hashref} = (
                   13433:                                 sums     => \%chksum,
                   13434:                                 versions => \%revnum,
                   13435:                               );
                   13436:             }
                   13437:         }
                   13438:     }
1.869     albertel 13439:     return;
1.852     albertel 13440: }
1.1172.2.17  raeburn  13441: 
                   13442: sub fetch_dns_checksums {
                   13443:     my %checksums;
1.1172.2.34  raeburn  13444:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13445:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13446:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13447:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13448:              \%checksums);
                   13449:     return \%checksums;
                   13450: }
                   13451: 
1.327     albertel 13452: # ------------------------------------------------------------ Read domain file
                   13453: {
1.852     albertel 13454:     my $loaded;
1.846     albertel 13455:     my %domain;
                   13456: 
1.852     albertel 13457:     sub parse_domain_tab {
                   13458: 	my ($lines) = @_;
                   13459: 	foreach my $line (@$lines) {
                   13460: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13461: 
1.846     albertel 13462: 	    chomp($line);
1.852     albertel 13463: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13464: 	    my %this_domain;
                   13465: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13466: 			       'lang_def', 'city', 'longi', 'lati',
                   13467: 			       'primary') {
                   13468: 		$this_domain{$field} = shift(@elements);
                   13469: 	    }
                   13470: 	    $domain{$name} = \%this_domain;
1.852     albertel 13471: 	}
                   13472:     }
1.864     albertel 13473: 
                   13474:     sub reset_domain_info {
                   13475: 	undef($loaded);
                   13476: 	undef(%domain);
                   13477:     }
                   13478: 
1.852     albertel 13479:     sub load_domain_tab {
1.1172.2.70  raeburn  13480: 	my ($ignore_cache,$nocache) = @_;
                   13481: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13482: 	my $fh;
1.1172.2.96  raeburn  13483: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13484: 	    my @lines = <$fh>;
                   13485: 	    &parse_domain_tab(\@lines);
1.448     albertel 13486: 	}
1.852     albertel 13487: 	close($fh);
                   13488: 	$loaded = 1;
1.327     albertel 13489:     }
1.846     albertel 13490: 
                   13491:     sub domain {
1.852     albertel 13492: 	&load_domain_tab() if (!$loaded);
                   13493: 
1.846     albertel 13494: 	my ($name,$what) = @_;
                   13495: 	return if ( !exists($domain{$name}) );
                   13496: 
                   13497: 	if (!$what) {
                   13498: 	    return $domain{$name}{'description'};
                   13499: 	}
                   13500: 	return $domain{$name}{$what};
                   13501:     }
1.974     raeburn  13502: 
                   13503:     sub domain_info {
                   13504:         &load_domain_tab() if (!$loaded);
                   13505:         return %domain;
                   13506:     }
                   13507: 
1.327     albertel 13508: }
                   13509: 
                   13510: 
1.1       albertel 13511: # ------------------------------------------------------------- Read hosts file
                   13512: {
1.838     albertel 13513:     my %hostname;
1.844     albertel 13514:     my %hostdom;
1.845     albertel 13515:     my %libserv;
1.852     albertel 13516:     my $loaded;
1.888     albertel 13517:     my %name_to_host;
1.1074    raeburn  13518:     my %internetdom;
1.1107    raeburn  13519:     my %LC_dns_serv;
1.852     albertel 13520: 
                   13521:     sub parse_hosts_tab {
                   13522: 	my ($file) = @_;
                   13523: 	foreach my $configline (@$file) {
                   13524: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13525:             chomp($configline);
                   13526: 	    if ($configline =~ /^\^/) {
                   13527:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13528:                     $LC_dns_serv{$1} = 1;
                   13529:                 }
                   13530:                 next;
                   13531:             }
1.1074    raeburn  13532: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13533: 	    $name=~s/\s//g;
                   13534: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13535:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13536:                     my $curr = $hostname{$id};
                   13537:                     my $skip;
                   13538:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13539:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13540:                             $skip = 1;
                   13541:                         } else {
                   13542:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13543:                         }
                   13544:                     }
                   13545:                     unless ($skip) {
                   13546:                         push(@{$name_to_host{$name}},$id);
                   13547:                     }
                   13548:                 } else {
                   13549:                     push(@{$name_to_host{$name}},$id);
                   13550:                 }
1.852     albertel 13551: 		$hostname{$id}=$name;
                   13552: 		$hostdom{$id}=$domain;
                   13553: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13554:                 if (defined($protocol)) {
                   13555:                     if ($protocol eq 'https') {
                   13556:                         $protocol{$id} = $protocol;
                   13557:                     } else {
                   13558:                         $protocol{$id} = 'http'; 
                   13559:                     }
1.968     raeburn  13560:                 } else {
1.969     raeburn  13561:                     $protocol{$id} = 'http';
1.968     raeburn  13562:                 }
1.1074    raeburn  13563:                 if (defined($intdom)) {
                   13564:                     $internetdom{$id} = $intdom;
                   13565:                 }
1.852     albertel 13566: 	    }
                   13567: 	}
                   13568:     }
1.864     albertel 13569:     
                   13570:     sub reset_hosts_info {
1.897     albertel 13571: 	&purge_remembered();
1.864     albertel 13572: 	&reset_domain_info();
                   13573: 	&reset_hosts_ip_info();
1.892     albertel 13574: 	undef(%name_to_host);
1.864     albertel 13575: 	undef(%hostname);
                   13576: 	undef(%hostdom);
                   13577: 	undef(%libserv);
                   13578: 	undef($loaded);
                   13579:     }
1.1       albertel 13580: 
1.852     albertel 13581:     sub load_hosts_tab {
1.1172.2.70  raeburn  13582: 	my ($ignore_cache,$nocache) = @_;
                   13583: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13584: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13585: 	my @config = <$config>;
                   13586: 	&parse_hosts_tab(\@config);
                   13587: 	close($config);
                   13588: 	$loaded=1;
1.1       albertel 13589:     }
1.852     albertel 13590: 
1.838     albertel 13591:     sub hostname {
1.852     albertel 13592: 	&load_hosts_tab() if (!$loaded);
                   13593: 
1.838     albertel 13594: 	my ($lonid) = @_;
                   13595: 	return $hostname{$lonid};
                   13596:     }
1.845     albertel 13597: 
1.838     albertel 13598:     sub all_hostnames {
1.852     albertel 13599: 	&load_hosts_tab() if (!$loaded);
                   13600: 
1.838     albertel 13601: 	return %hostname;
                   13602:     }
1.845     albertel 13603: 
1.888     albertel 13604:     sub all_names {
1.1172.2.70  raeburn  13605:         my ($ignore_cache,$nocache) = @_;
                   13606: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13607: 
                   13608: 	return %name_to_host;
                   13609:     }
                   13610: 
1.974     raeburn  13611:     sub all_host_domain {
                   13612:         &load_hosts_tab() if (!$loaded);
                   13613:         return %hostdom;
                   13614:     }
                   13615: 
1.845     albertel 13616:     sub is_library {
1.852     albertel 13617: 	&load_hosts_tab() if (!$loaded);
                   13618: 
1.845     albertel 13619: 	return exists($libserv{$_[0]});
                   13620:     }
                   13621: 
                   13622:     sub all_library {
1.852     albertel 13623: 	&load_hosts_tab() if (!$loaded);
                   13624: 
1.845     albertel 13625: 	return %libserv;
                   13626:     }
                   13627: 
1.1062    droeschl 13628:     sub unique_library {
                   13629: 	#2x reverse removes all hostnames that appear more than once
                   13630:         my %unique = reverse &all_library();
                   13631:         return reverse %unique;
                   13632:     }
                   13633: 
1.841     albertel 13634:     sub get_servers {
1.852     albertel 13635: 	&load_hosts_tab() if (!$loaded);
                   13636: 
1.841     albertel 13637: 	my ($domain,$type) = @_;
                   13638: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13639: 	                                          : %hostname;
                   13640: 	my %result;
1.842     albertel 13641: 	if (ref($domain) eq 'ARRAY') {
                   13642: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13643: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13644: 		    $result{$host} = $hostname;
                   13645: 		}
                   13646: 	    }
                   13647: 	} else {
                   13648: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13649: 		if ($hostdom{$host} eq $domain) {
                   13650: 		    $result{$host} = $hostname;
                   13651: 		}
1.841     albertel 13652: 	    }
                   13653: 	}
                   13654: 	return %result;
                   13655:     }
1.845     albertel 13656: 
1.1062    droeschl 13657:     sub get_unique_servers {
                   13658:         my %unique = reverse &get_servers(@_);
                   13659: 	return reverse %unique;
                   13660:     }
                   13661: 
1.844     albertel 13662:     sub host_domain {
1.852     albertel 13663: 	&load_hosts_tab() if (!$loaded);
                   13664: 
1.844     albertel 13665: 	my ($lonid) = @_;
                   13666: 	return $hostdom{$lonid};
                   13667:     }
                   13668: 
1.841     albertel 13669:     sub all_domains {
1.852     albertel 13670: 	&load_hosts_tab() if (!$loaded);
                   13671: 
1.841     albertel 13672: 	my %seen;
                   13673: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13674: 	return @uniq;
                   13675:     }
1.1074    raeburn  13676: 
                   13677:     sub internet_dom {
                   13678:         &load_hosts_tab() if (!$loaded);
                   13679: 
                   13680:         my ($lonid) = @_;
                   13681:         return $internetdom{$lonid};
                   13682:     }
1.1107    raeburn  13683: 
                   13684:     sub is_LC_dns {
                   13685:         &load_hosts_tab() if (!$loaded);
                   13686: 
                   13687:         my ($hostname) = @_;
                   13688:         return exists($LC_dns_serv{$hostname});
                   13689:     }
                   13690: 
1.1       albertel 13691: }
                   13692: 
1.847     albertel 13693: { 
                   13694:     my %iphost;
1.856     albertel 13695:     my %name_to_ip;
                   13696:     my %lonid_to_ip;
1.869     albertel 13697: 
1.847     albertel 13698:     sub get_hosts_from_ip {
                   13699: 	my ($ip) = @_;
                   13700: 	my %iphosts = &get_iphost();
                   13701: 	if (ref($iphosts{$ip})) {
                   13702: 	    return @{$iphosts{$ip}};
                   13703: 	}
                   13704: 	return;
1.839     albertel 13705:     }
1.864     albertel 13706:     
                   13707:     sub reset_hosts_ip_info {
                   13708: 	undef(%iphost);
                   13709: 	undef(%name_to_ip);
                   13710: 	undef(%lonid_to_ip);
                   13711:     }
1.856     albertel 13712: 
                   13713:     sub get_host_ip {
                   13714: 	my ($lonid) = @_;
                   13715: 	if (exists($lonid_to_ip{$lonid})) {
                   13716: 	    return $lonid_to_ip{$lonid};
                   13717: 	}
                   13718: 	my $name=&hostname($lonid);
                   13719:    	my $ip = gethostbyname($name);
                   13720: 	return if (!$ip || length($ip) ne 4);
                   13721: 	$ip=inet_ntoa($ip);
                   13722: 	$name_to_ip{$name}   = $ip;
                   13723: 	$lonid_to_ip{$lonid} = $ip;
                   13724: 	return $ip;
                   13725:     }
1.847     albertel 13726:     
                   13727:     sub get_iphost {
1.1172.2.70  raeburn  13728: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13729: 
1.869     albertel 13730: 	if (!$ignore_cache) {
                   13731: 	    if (%iphost) {
                   13732: 		return %iphost;
                   13733: 	    }
                   13734: 	    my ($ip_info,$cached)=
                   13735: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13736: 	    if ($cached) {
                   13737: 		%iphost      = %{$ip_info->[0]};
                   13738: 		%name_to_ip  = %{$ip_info->[1]};
                   13739: 		%lonid_to_ip = %{$ip_info->[2]};
                   13740: 		return %iphost;
                   13741: 	    }
                   13742: 	}
1.894     albertel 13743: 
                   13744: 	# get yesterday's info for fallback
                   13745: 	my %old_name_to_ip;
                   13746: 	my ($ip_info,$cached)=
                   13747: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13748: 	if ($cached) {
                   13749: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13750: 	}
                   13751: 
1.1172.2.70  raeburn  13752: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13753: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13754: 	    my $ip;
                   13755: 	    if (!exists($name_to_ip{$name})) {
                   13756: 		$ip = gethostbyname($name);
                   13757: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13758: 		    if (defined($old_name_to_ip{$name})) {
                   13759: 			$ip = $old_name_to_ip{$name};
                   13760: 			&logthis("Can't find $name defaulting to old $ip");
                   13761: 		    } else {
                   13762: 			&logthis("Name $name no IP found");
                   13763: 			next;
                   13764: 		    }
                   13765: 		} else {
                   13766: 		    $ip=inet_ntoa($ip);
1.847     albertel 13767: 		}
                   13768: 		$name_to_ip{$name} = $ip;
                   13769: 	    } else {
                   13770: 		$ip = $name_to_ip{$name};
1.653     albertel 13771: 	    }
1.888     albertel 13772: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13773: 		$lonid_to_ip{$id} = $ip;
                   13774: 	    }
                   13775: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13776: 	}
1.1172.2.70  raeburn  13777:         unless ($nocache) {
                   13778: 	    &do_cache_new('iphost','iphost',
                   13779: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13780: 		          48*60*60);
                   13781:         }
1.869     albertel 13782: 
1.847     albertel 13783: 	return %iphost;
1.598     albertel 13784:     }
                   13785: 
1.992     raeburn  13786:     #
                   13787:     #  Given a DNS returns the loncapa host name for that DNS 
                   13788:     # 
                   13789:     sub host_from_dns {
                   13790:         my ($dns) = @_;
                   13791:         my @hosts;
                   13792:         my $ip;
                   13793: 
1.993     raeburn  13794:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13795:             $ip = $name_to_ip{$dns};
                   13796:         }
                   13797:         if (!$ip) {
                   13798:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13799:             if (length($ip) == 4) { 
                   13800: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13801:             }
                   13802:         }
                   13803:         if ($ip) {
                   13804: 	    @hosts = get_hosts_from_ip($ip);
                   13805: 	    return $hosts[0];
                   13806:         }
                   13807:         return undef;
1.986     foxr     13808:     }
1.992     raeburn  13809: 
1.1074    raeburn  13810:     sub get_internet_names {
                   13811:         my ($lonid) = @_;
                   13812:         return if ($lonid eq '');
                   13813:         my ($idnref,$cached)=
                   13814:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13815:         if ($cached) {
                   13816:             return $idnref;
                   13817:         }
                   13818:         my $ip = &get_host_ip($lonid);
                   13819:         my @hosts = &get_hosts_from_ip($ip);
                   13820:         my %iphost = &get_iphost();
                   13821:         my (@idns,%seen);
                   13822:         foreach my $id (@hosts) {
                   13823:             my $dom = &host_domain($id);
                   13824:             my $prim_id = &domain($dom,'primary');
                   13825:             my $prim_ip = &get_host_ip($prim_id);
                   13826:             next if ($seen{$prim_ip});
                   13827:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13828:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13829:                     my $intdom = &internet_dom($id);
                   13830:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13831:                         push(@idns,$intdom);
                   13832:                     }
                   13833:                 }
                   13834:             }
                   13835:             $seen{$prim_ip} = 1;
                   13836:         }
1.1172.2.23  raeburn  13837:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13838:     }
                   13839: 
1.986     foxr     13840: }
                   13841: 
1.1079    raeburn  13842: sub all_loncaparevs {
1.1172.2.39  raeburn  13843:     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  13844: }
                   13845: 
1.1172.2.27  raeburn  13846: # ------------------------------------------------------- Read loncaparev table
                   13847: {
                   13848:     sub load_loncaparevs {
                   13849:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13850:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13851:                 while (my $configline=<$config>) {
                   13852:                     chomp($configline);
                   13853:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13854:                     $loncaparevs{$hostid}=$loncaparev;
                   13855:                 }
                   13856:                 close($config);
                   13857:             }
                   13858:         }
                   13859:     }
                   13860: }
                   13861: 
                   13862: # ----------------------------------------------------- Read serverhostID table
                   13863: {
                   13864:     sub load_serverhomeIDs {
                   13865:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13866:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13867:                 while (my $configline=<$config>) {
                   13868:                     chomp($configline);
                   13869:                     my ($name,$id)=split(/:/,$configline);
                   13870:                     $serverhomeIDs{$name}=$id;
                   13871:                 }
                   13872:                 close($config);
                   13873:             }
                   13874:         }
                   13875:     }
                   13876: }
                   13877: 
                   13878: 
1.862     albertel 13879: BEGIN {
                   13880: 
                   13881: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13882:     unless ($readit) {
                   13883: {
                   13884:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13885:     %perlvar = (%perlvar,%{$configvars});
                   13886: }
                   13887: 
                   13888: 
1.1       albertel 13889: # ------------------------------------------------------ Read spare server file
                   13890: {
1.1172.2.96  raeburn  13891:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13892: 
                   13893:     while (my $configline=<$config>) {
                   13894:        chomp($configline);
1.284     matthew  13895:        if ($configline) {
1.784     albertel 13896: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13897: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13898: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13899:        }
                   13900:     }
1.448     albertel 13901:     close($config);
1.1       albertel 13902: }
1.11      www      13903: # ------------------------------------------------------------ Read permissions
                   13904: {
1.1172.2.96  raeburn  13905:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13906: 
                   13907:     while (my $configline=<$config>) {
1.448     albertel 13908: 	chomp($configline);
                   13909: 	if ($configline) {
                   13910: 	    my ($role,$perm)=split(/ /,$configline);
                   13911: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13912: 	}
1.11      www      13913:     }
1.448     albertel 13914:     close($config);
1.11      www      13915: }
                   13916: 
                   13917: # -------------------------------------------- Read plain texts for permissions
                   13918: {
1.1172.2.96  raeburn  13919:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13920: 
                   13921:     while (my $configline=<$config>) {
1.448     albertel 13922: 	chomp($configline);
                   13923: 	if ($configline) {
1.742     raeburn  13924: 	    my ($short,@plain)=split(/:/,$configline);
                   13925:             %{$prp{$short}} = ();
                   13926: 	    if (@plain > 0) {
                   13927:                 $prp{$short}{'std'} = $plain[0];
                   13928:                 for (my $i=1; $i<@plain; $i++) {
                   13929:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13930:                 }
                   13931:             }
1.448     albertel 13932: 	}
1.135     www      13933:     }
1.448     albertel 13934:     close($config);
1.135     www      13935: }
                   13936: 
                   13937: # ---------------------------------------------------------- Read package table
                   13938: {
1.1172.2.96  raeburn  13939:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13940: 
                   13941:     while (my $configline=<$config>) {
1.483     albertel 13942: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13943: 	chomp($configline);
                   13944: 	my ($short,$plain)=split(/:/,$configline);
                   13945: 	my ($pack,$name)=split(/\&/,$short);
                   13946: 	if ($plain ne '') {
                   13947: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13948: 	    $packagetab{$short}=$plain; 
                   13949: 	}
1.11      www      13950:     }
1.448     albertel 13951:     close($config);
1.329     matthew  13952: }
                   13953: 
1.1172.2.27  raeburn  13954: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13955: 
1.1172.2.27  raeburn  13956: &load_loncaparevs();
                   13957: 
                   13958: # ------------------------------------------------------- Read serverhostID table
                   13959: 
                   13960: &load_serverhomeIDs();
1.1074    raeburn  13961: 
1.1172.2.27  raeburn  13962: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13963: {
                   13964:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13965:     if (-e $file) {
                   13966:         my $parser = HTML::LCParser->new($file);
                   13967:         while (my $token = $parser->get_token()) {
                   13968:             if ($token->[0] eq 'S') {
                   13969:                 my $item = $token->[1];
                   13970:                 my $name = $token->[2]{'name'};
                   13971:                 my $value = $token->[2]{'value'};
                   13972:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13973:                     my $release = $parser->get_text();
                   13974:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13975:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13976:                 }
                   13977:             }
                   13978:         }
                   13979:     }
1.1073    raeburn  13980: }
                   13981: 
1.1138    raeburn  13982: # ---------------------------------------------------------- Read managers table
                   13983: {
                   13984:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13985:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13986:             while (my $configline=<$config>) {
                   13987:                 chomp($configline);
                   13988:                 next if ($configline =~ /^\#/);
                   13989:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13990:                     $managerstab{$configline} = 1;
                   13991:                 }
                   13992:             }
                   13993:             close($config);
                   13994:         }
                   13995:     }
                   13996: }
                   13997: 
1.329     matthew  13998: # ------------- set up temporary directory
                   13999: {
1.1117    foxr     14000:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14001: 
1.11      www      14002: }
                   14003: 
1.1172.2.104  raeburn  14004: # ------------- set default texengine (domain default overrides this)
                   14005: {
                   14006:     $deftex = LONCAPA::texengine();
                   14007: }
                   14008: 
1.1172.2.114  raeburn  14009: # ------------- set default minimum length for passwords for internal auth users
                   14010: {
                   14011:     $passwdmin = LONCAPA::passwd_min();
                   14012: }
                   14013: 
1.794     albertel 14014: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14015: 				'compress_threshold'=> 20_000,
                   14016:  			        });
1.185     www      14017: 
1.281     www      14018: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14019: $dumpcount=0;
1.958     www      14020: $locknum=0;
1.22      www      14021: 
1.163     harris41 14022: &logtouch();
1.672     albertel 14023: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14024: $readit=1;
1.564     albertel 14025:     {
                   14026: 	use integer;
                   14027: 	my $test=(2**32)+1;
1.568     albertel 14028: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14029: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14030:     }
1.195     www      14031: }
1.1       albertel 14032: }
1.179     www      14033: 
1.1       albertel 14034: 1;
1.191     harris41 14035: __END__
                   14036: 
1.243     albertel 14037: =pod
                   14038: 
1.191     harris41 14039: =head1 NAME
                   14040: 
1.243     albertel 14041: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14042: 
                   14043: =head1 SYNOPSIS
                   14044: 
1.243     albertel 14045: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14046: 
                   14047:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14048: 
1.243     albertel 14049: Common parameters:
                   14050: 
                   14051: =over 4
                   14052: 
                   14053: =item *
                   14054: 
                   14055: $uname : an internal username (if $cname expecting a course Id specifically)
                   14056: 
                   14057: =item *
                   14058: 
                   14059: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14060: 
                   14061: =item *
                   14062: 
                   14063: $symb : a resource instance identifier
                   14064: 
                   14065: =item *
                   14066: 
                   14067: $namespace : the name of a .db file that contains the data needed or
                   14068: being set.
                   14069: 
                   14070: =back
                   14071: 
1.394     bowersj2 14072: =head1 OVERVIEW
1.191     harris41 14073: 
1.394     bowersj2 14074: lonnet provides subroutines which interact with the
                   14075: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14076: about classes, users, and resources.
1.243     albertel 14077: 
                   14078: For many of these objects you can also use this to store data about
                   14079: them or modify them in various ways.
1.191     harris41 14080: 
1.394     bowersj2 14081: =head2 Symbs
1.191     harris41 14082: 
1.394     bowersj2 14083: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14084: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14085: map, the resource number of the resource in the map, and the URL of
                   14086: the resource itself. The latter is somewhat redundant, but might help
                   14087: if maps change.
                   14088: 
                   14089: An example is
                   14090: 
                   14091:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14092: 
                   14093: The respective map entry is
                   14094: 
                   14095:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14096:   title="Problem 2">
                   14097:  </resource>
                   14098: 
                   14099: Symbs are used by the random number generator, as well as to store and
                   14100: restore data specific to a certain instance of for example a problem.
                   14101: 
                   14102: =head2 Storing And Retrieving Data
                   14103: 
                   14104: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14105: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14106: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14107: is is the non-critical message twin of cstore. These functions are for
                   14108: handlers to store a perl hash to a user's permanent data space in an
                   14109: easy manner, and to retrieve it again on another call. It is expected
                   14110: that a handler would use this once at the beginning to retrieve data,
                   14111: and then again once at the end to send only the new data back.
                   14112: 
                   14113: The data is stored in the user's data directory on the user's
                   14114: homeserver under the ID of the course.
                   14115: 
                   14116: The hash that is returned by restore will have all of the previous
                   14117: value for all of the elements of the hash.
                   14118: 
                   14119: Example:
                   14120: 
                   14121:  #creating a hash
                   14122:  my %hash;
                   14123:  $hash{'foo'}='bar';
                   14124: 
                   14125:  #storing it
                   14126:  &Apache::lonnet::cstore(\%hash);
                   14127: 
                   14128:  #changing a value
                   14129:  $hash{'foo'}='notbar';
                   14130: 
                   14131:  #adding a new value
                   14132:  $hash{'bar'}='foo';
                   14133:  &Apache::lonnet::cstore(\%hash);
                   14134: 
                   14135:  #retrieving the hash
                   14136:  my %history=&Apache::lonnet::restore();
                   14137: 
                   14138:  #print the hash
                   14139:  foreach my $key (sort(keys(%history))) {
                   14140:    print("\%history{$key} = $history{$key}");
                   14141:  }
                   14142: 
                   14143: Will print out:
1.191     harris41 14144: 
1.394     bowersj2 14145:  %history{1:foo} = bar
                   14146:  %history{1:keys} = foo:timestamp
                   14147:  %history{1:timestamp} = 990455579
                   14148:  %history{2:bar} = foo
                   14149:  %history{2:foo} = notbar
                   14150:  %history{2:keys} = foo:bar:timestamp
                   14151:  %history{2:timestamp} = 990455580
                   14152:  %history{bar} = foo
                   14153:  %history{foo} = notbar
                   14154:  %history{timestamp} = 990455580
                   14155:  %history{version} = 2
                   14156: 
                   14157: Note that the special hash entries C<keys>, C<version> and
                   14158: C<timestamp> were added to the hash. C<version> will be equal to the
                   14159: total number of versions of the data that have been stored. The
                   14160: C<timestamp> attribute will be the UNIX time the hash was
                   14161: stored. C<keys> is available in every historical section to list which
                   14162: keys were added or changed at a specific historical revision of a
                   14163: hash.
                   14164: 
                   14165: B<Warning>: do not store the hash that restore returns directly. This
                   14166: will cause a mess since it will restore the historical keys as if the
                   14167: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14168: 
1.394     bowersj2 14169: Calling convention:
1.191     harris41 14170: 
1.1172.2.27  raeburn  14171:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14172:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14173: 
1.394     bowersj2 14174: For more detailed information, see lonnet specific documentation.
1.191     harris41 14175: 
1.394     bowersj2 14176: =head1 RETURN MESSAGES
1.191     harris41 14177: 
1.394     bowersj2 14178: =over 4
1.191     harris41 14179: 
1.394     bowersj2 14180: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14181: 
1.394     bowersj2 14182: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14183: when the connection is brought back up
1.191     harris41 14184: 
1.394     bowersj2 14185: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14186: for later delivery
1.191     harris41 14187: 
1.967     bisitz   14188: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14189: 
1.394     bowersj2 14190: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14191: that was requested
1.191     harris41 14192: 
1.243     albertel 14193: =back
1.191     harris41 14194: 
1.243     albertel 14195: =head1 PUBLIC SUBROUTINES
1.191     harris41 14196: 
1.243     albertel 14197: =head2 Session Environment Functions
1.191     harris41 14198: 
1.243     albertel 14199: =over 4
1.191     harris41 14200: 
1.394     bowersj2 14201: =item * 
                   14202: X<appenv()>
1.949     raeburn  14203: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14204: the user envirnoment file, and will be restored for each access this
1.620     albertel 14205: user makes during this session, also modifies the %env for the current
1.949     raeburn  14206: process. Optional rolesarrayref - if defined contains a reference to an array
                   14207: of roles which are exempt from the restriction on modifying user.role entries 
                   14208: in the user's environment.db and in %env.    
1.191     harris41 14209: 
                   14210: =item *
1.394     bowersj2 14211: X<delenv()>
1.987     raeburn  14212: B<delenv($delthis,$regexp)>: removes all items from the session
                   14213: environment file that begin with $delthis. If the 
                   14214: optional second arg - $regexp - is true, $delthis is treated as a 
                   14215: regular expression, otherwise \Q$delthis\E is used. 
                   14216: The values are also deleted from the current processes %env.
1.191     harris41 14217: 
1.795     albertel 14218: =item * get_env_multiple($name) 
                   14219: 
                   14220: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14221: values may be defined and end up as an array ref.
                   14222: 
                   14223: returns an array of values
                   14224: 
1.243     albertel 14225: =back
                   14226: 
                   14227: =head2 User Information
1.191     harris41 14228: 
1.243     albertel 14229: =over 4
1.191     harris41 14230: 
                   14231: =item *
1.394     bowersj2 14232: X<queryauthenticate()>
                   14233: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14234: authentication scheme
                   14235: 
                   14236: =item *
1.394     bowersj2 14237: X<authenticate()>
1.1073    raeburn  14238: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14239: authenticate user from domain's lib servers (first use the current
                   14240: one). C<$upass> should be the users password.
1.1073    raeburn  14241: $checkdefauth is optional (value is 1 if a check should be made to
                   14242:    authenticate user using default authentication method, and allow
                   14243:    account creation if username does not have account in the domain).
                   14244: $clientcancheckhost is optional (value is 1 if checking whether the
                   14245:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14246: 
                   14247: =item *
1.394     bowersj2 14248: X<homeserver()>
                   14249: B<homeserver($uname,$udom)>: find the server which has
                   14250: the user's directory and files (there must be only one), this caches
                   14251: the answer, and also caches if there is a borken connection.
1.191     harris41 14252: 
                   14253: =item *
1.394     bowersj2 14254: X<idget()>
                   14255: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14256: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14257: username, and only 1 username per ID in a specific domain) (returns
                   14258: hash: id=>name,id=>name)
1.191     harris41 14259: 
                   14260: =item *
1.394     bowersj2 14261: X<idrget()>
                   14262: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14263: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14264: 
                   14265: =item *
1.394     bowersj2 14266: X<idput()>
                   14267: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14268: 
                   14269: =item *
1.394     bowersj2 14270: X<rolesinit()>
1.1169    droeschl 14271: B<rolesinit($udom,$username)>: get user privileges.
                   14272: returns user role, first access and timer interval hashes
1.243     albertel 14273: 
                   14274: =item *
1.1171    droeschl 14275: X<privileged()>
                   14276: B<privileged($username,$domain)>: returns a true if user has a
                   14277: privileged and active role (i.e. su or dc), false otherwise.
                   14278: 
                   14279: =item *
1.551     albertel 14280: X<getsection()>
                   14281: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14282: course $cname, return section name/number or '' for "not in course"
                   14283: and '-1' for "no section"
                   14284: 
                   14285: =item *
1.394     bowersj2 14286: X<userenvironment()>
                   14287: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14288: passed in @what from the requested user's environment, returns a hash
                   14289: 
1.858     raeburn  14290: =item * 
                   14291: X<userlog_query()>
1.859     albertel 14292: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14293: activity.log file. %filters defines filters applied when parsing the
                   14294: log file. These can be start or end timestamps, or the type of action
                   14295: - log to look for Login or Logout events, check for Checkin or
                   14296: Checkout, role for role selection. The response is in the form
                   14297: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14298: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14299: 
1.243     albertel 14300: =back
                   14301: 
                   14302: =head2 User Roles
                   14303: 
                   14304: =over 4
                   14305: 
                   14306: =item *
                   14307: 
1.1172.2.65  raeburn  14308: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14309: returns codes for allowed actions.
                   14310: 
                   14311: The first argument is required, all others are optional.
                   14312: 
                   14313: $priv is the privilege being checked.
                   14314: $uri contains additional information about what is being checked for access (e.g.,
                   14315: URL, course ID etc.).
                   14316: $symb is the unique resource instance identifier in a course; if needed,
                   14317: but not provided, it will be retrieved via a call to &symbread().
                   14318: $role is the role for which a priv is being checked (only used if priv is evb).
                   14319: $clientip is the user's IP address (only used when checking for access to portfolio
                   14320: files).
                   14321: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14322: prevents recursive calls to &allowed.
                   14323: 
1.243     albertel 14324:  F: full access
                   14325:  U,I,K: authentication modes (cxx only)
                   14326:  '': forbidden
                   14327:  1: user needs to choose course
                   14328:  2: browse allowed
1.766     albertel 14329:  A: passphrase authentication needed
1.1172.2.65  raeburn  14330:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14331: 
                   14332: =item *
                   14333: 
1.1172.2.13  raeburn  14334: constructaccess($url,$setpriv) : check for access to construction space URL
                   14335: 
                   14336: See if the owner domain and name in the URL match those in the
                   14337: expected environment.  If so, return three element list
                   14338: ($ownername,$ownerdomain,$ownerhome).
                   14339: 
                   14340: Otherwise return the null string.
                   14341: 
                   14342: If second argument 'setpriv' is true, it assigns the privileges,
                   14343: and returns the same three element list, unless the owner has
                   14344: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14345: in which case the null string is returned.
                   14346: 
                   14347: =item *
                   14348: 
1.1172.2.84  raeburn  14349: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14350: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14351: for system, domain, and course level. $uname and $udom are optional (current
                   14352: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14353: 
                   14354: =item *
                   14355: 
1.988     raeburn  14356: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14357: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14358: $type is Course (default) or Community.
1.988     raeburn  14359: If $forcedefault evaluates to true, text returned will be default 
                   14360: text for $type. Otherwise, if this is a course, the text returned 
                   14361: will be a custom name for the role (if defined in the course's 
                   14362: environment).  If no custom name is defined the default is returned.
                   14363:    
1.832     raeburn  14364: =item *
                   14365: 
1.1172.2.23  raeburn  14366: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14367: All arguments are optional. Returns a hash of a roles, either for
                   14368: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14369: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14370: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14371: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14372: For each key, value is set to colon-separated start and end times for
                   14373: the role.  If no username and domain are specified, will default to
1.934     raeburn  14374: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14375: of role statuses (active, future or previous), roles 
                   14376: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14377: to restrict the list of roles reported. If no array ref is 
                   14378: provided for types, will default to return only active roles.
1.834     albertel 14379: 
1.1172.2.13  raeburn  14380: =item *
                   14381: 
                   14382: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14383: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14384: 
                   14385: Additional optional arguments are: $type (if role checking is to be restricted
                   14386: to certain user status types -- previous (expired roles), active (currently
                   14387: available roles) or future (roles available in the future), and
                   14388: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14389: have active Domain Coordinator role in course's domain or in additional
                   14390: domains (specified in 'Domains to check for privileged users' in course
                   14391: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14392: 
                   14393: =item *
                   14394: 
                   14395: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14396: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14397: $possdomains and $possroles are optional array refs -- to domains to check and
                   14398: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14399: users' roles.db to check for a dc or su role in any domain. This can be
                   14400: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14401: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14402: this then allows &privileged_by_domain() to be used, which caches the identity
                   14403: of privileged users, eliminating the need for repeated calls to &dump().
                   14404: 
                   14405: =item *
                   14406: 
                   14407: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14408: where the outer hash keys are domains specified in the $possdomains array ref,
                   14409: next inner hash keys are privileged roles specified in the $roles array ref,
                   14410: and the innermost hash contains key = value pairs for username:domain = end:start
                   14411: for active or future "privileged" users with that role in that domain. To avoid
                   14412: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14413: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14414: 
1.243     albertel 14415: =back
                   14416: 
                   14417: =head2 User Modification
                   14418: 
                   14419: =over 4
                   14420: 
                   14421: =item *
                   14422: 
1.957     raeburn  14423: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14424: user for the level given by URL.  Optional start and end dates (leave empty
                   14425: string or zero for "no date")
1.191     harris41 14426: 
                   14427: =item *
                   14428: 
1.243     albertel 14429: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14430: change a users, password, possible return values are: ok,
                   14431: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14432: refused
1.191     harris41 14433: 
                   14434: =item *
                   14435: 
1.243     albertel 14436: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14437: 
                   14438: =item *
                   14439: 
1.1058    raeburn  14440: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14441:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14442: 
                   14443: will update user information (firstname,middlename,lastname,generation,
                   14444: permanentemail), and if forceid is true, student/employee ID also.
                   14445: A user's institutional affiliation(s) can also be updated.
                   14446: User information fields will not be overwritten with empty entries 
                   14447: unless the field is included in the $candelete array reference.
                   14448: This array is included when a single user is modified via "Manage Users",
                   14449: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14450: 
                   14451: =item *
                   14452: 
1.286     matthew  14453: modifystudent
                   14454: 
1.957     raeburn  14455: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14456: The course id is resolved based on the current user's environment.  
                   14457: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14458: associated with a course.
                   14459: 
1.297     matthew  14460: This call is essentially a wrapper for lonnet::modifyuser and
                   14461: lonnet::modify_student_enrollment
1.286     matthew  14462: 
                   14463: Inputs: 
                   14464: 
                   14465: =over 4
                   14466: 
1.957     raeburn  14467: =item B<$udom> Student's loncapa domain
1.286     matthew  14468: 
1.957     raeburn  14469: =item B<$uname> Student's loncapa login name
1.286     matthew  14470: 
1.964     bisitz   14471: =item B<$uid> Student/Employee ID
1.286     matthew  14472: 
1.957     raeburn  14473: =item B<$umode> Student's authentication mode
1.286     matthew  14474: 
1.957     raeburn  14475: =item B<$upass> Student's password
1.286     matthew  14476: 
1.957     raeburn  14477: =item B<$first> Student's first name
1.286     matthew  14478: 
1.957     raeburn  14479: =item B<$middle> Student's middle name
1.286     matthew  14480: 
1.957     raeburn  14481: =item B<$last> Student's last name
1.286     matthew  14482: 
1.957     raeburn  14483: =item B<$gene> Student's generation
1.286     matthew  14484: 
1.957     raeburn  14485: =item B<$usec> Student's section in course
1.286     matthew  14486: 
                   14487: =item B<$end> Unix time of the roles expiration
                   14488: 
                   14489: =item B<$start> Unix time of the roles start date
                   14490: 
                   14491: =item B<$forceid> If defined, allow $uid to be changed
                   14492: 
                   14493: =item B<$desiredhome> server to use as home server for student
                   14494: 
1.957     raeburn  14495: =item B<$email> Student's permanent e-mail address
                   14496: 
                   14497: =item B<$type> Type of enrollment (auto or manual)
                   14498: 
1.963     raeburn  14499: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14500: 
                   14501: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14502: 
1.963     raeburn  14503: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14504: 
1.963     raeburn  14505: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14506: 
1.1172.2.19  raeburn  14507: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14508: 
                   14509: =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  14510: 
1.286     matthew  14511: =back
1.297     matthew  14512: 
                   14513: =item *
                   14514: 
                   14515: modify_student_enrollment
                   14516: 
1.1172.2.31  raeburn  14517: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14518: 'role.request.course' must be defined for this function to proceed.
                   14519: 
                   14520: Inputs:
                   14521: 
                   14522: =over 4
                   14523: 
1.1172.2.31  raeburn  14524: =item $udom, student's domain
1.297     matthew  14525: 
1.1172.2.31  raeburn  14526: =item $uname, student's name
1.297     matthew  14527: 
1.1172.2.31  raeburn  14528: =item $uid, student's user id
1.297     matthew  14529: 
1.1172.2.31  raeburn  14530: =item $first, student's first name
1.297     matthew  14531: 
                   14532: =item $middle
                   14533: 
                   14534: =item $last
                   14535: 
                   14536: =item $gene
                   14537: 
                   14538: =item $usec
                   14539: 
                   14540: =item $end
                   14541: 
                   14542: =item $start
                   14543: 
1.957     raeburn  14544: =item $type
                   14545: 
                   14546: =item $locktype
                   14547: 
                   14548: =item $cid
                   14549: 
                   14550: =item $selfenroll
                   14551: 
                   14552: =item $context
                   14553: 
1.1172.2.19  raeburn  14554: =item $credits, number of credits student will earn from this class
                   14555: 
1.1172.2.76  raeburn  14556: =item $instsec, institutional course section code for student
                   14557: 
1.297     matthew  14558: =back
                   14559: 
1.191     harris41 14560: 
                   14561: =item *
                   14562: 
1.243     albertel 14563: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14564: custom role; give a custom role to a user for the level given by URL.  Specify
                   14565: name and domain of role author, and role name
1.191     harris41 14566: 
                   14567: =item *
                   14568: 
1.243     albertel 14569: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14570: 
                   14571: =item *
                   14572: 
1.243     albertel 14573: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14574: 
                   14575: =back
                   14576: 
                   14577: =head2 Course Infomation
                   14578: 
                   14579: =over 4
1.191     harris41 14580: 
                   14581: =item *
                   14582: 
1.1118    foxr     14583: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14584: specified course id, including all environment settings for the
                   14585: course, the description of the course will be in the hash under the
                   14586: key 'description'
1.191     harris41 14587: 
1.1118    foxr     14588: $options is an optional parameter that if supplied is a hash reference that controls
                   14589: what how this function works.  It has the following key/values:
                   14590: 
                   14591: =over 4
                   14592: 
                   14593: =item freshen_cache
                   14594: 
                   14595: If defined, and the environment cache for the course is valid, it is 
                   14596: returned in the returned hash.
                   14597: 
                   14598: =item one_time
                   14599: 
                   14600: If defined, the last cache time is set to _now_
                   14601: 
                   14602: =item user
                   14603: 
                   14604: If defined, the supplied username is used instead of the current user.
                   14605: 
                   14606: 
                   14607: =back
                   14608: 
1.191     harris41 14609: =item *
                   14610: 
1.624     albertel 14611: resdata($name,$domain,$type,@which) : request for current parameter
                   14612: setting for a specific $type, where $type is either 'course' or 'user',
                   14613: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14614: answers for 10 minutes.
1.243     albertel 14615: 
1.877     foxr     14616: =item *
                   14617: 
                   14618: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14619: data base, returning a hash that is keyed by the resource name and has
                   14620: values that are the resource value.  I believe that the timestamps and
                   14621: versions are also returned.
                   14622: 
1.1172.2.31  raeburn  14623: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14624: supplemental content area. This routine caches the number of files for
                   14625: 10 minutes.
                   14626: 
1.243     albertel 14627: =back
                   14628: 
                   14629: =head2 Course Modification
                   14630: 
                   14631: =over 4
1.191     harris41 14632: 
                   14633: =item *
                   14634: 
1.243     albertel 14635: writecoursepref($courseid,%prefs) : write preferences (environment
                   14636: database) for a course
1.191     harris41 14637: 
                   14638: =item *
                   14639: 
1.1011    raeburn  14640: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14641: 
                   14642: =item *
                   14643: 
1.1038    raeburn  14644: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14645: 
1.1167    droeschl 14646: =item *
                   14647: 
                   14648: is_course($courseid), is_course($cdom, $cnum)
                   14649: 
                   14650: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14651: two component version $cdom, $cnum. It checks if the specified course exists.
                   14652: 
                   14653: Returns:
                   14654:     undef if the course doesn't exist, otherwise
                   14655:     in scalar context the combined courseid.
                   14656:     in list context the two components of the course identifier, domain and 
                   14657:     courseid.    
                   14658: 
1.243     albertel 14659: =back
                   14660: 
1.1172.2.109  raeburn  14661: =head2 Bubblesheet Configuration
                   14662: 
                   14663: =over 4
                   14664: 
                   14665: =item *
                   14666: 
                   14667: get_scantron_config($which)
                   14668: 
                   14669: $which - the name of the configuration to parse from the file.
                   14670: 
                   14671: Parses and returns the bubblesheet configuration line selected as a
                   14672: hash of configuration file fields.
                   14673: 
                   14674: 
                   14675: Returns:
                   14676:     If the named configuration is not in the file, an empty
                   14677:     hash is returned.
                   14678: 
                   14679:     a hash with the fields
                   14680:       name         - internal name for the this configuration setup
                   14681:       description  - text to display to operator that describes this config
                   14682:       CODElocation - if 0 or the string 'none'
                   14683:                           - no CODE exists for this config
                   14684:                      if -1 || the string 'letter'
                   14685:                           - a CODE exists for this config and is
                   14686:                             a string of letters
                   14687:                      Unsupported value (but planned for future support)
                   14688:                           if a positive integer
                   14689:                                - The CODE exists as the first n items from
                   14690:                                  the question section of the form
                   14691:                           if the string 'number'
                   14692:                                - The CODE exists for this config and is
                   14693:                                  a string of numbers
                   14694:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14695:                      the CODE starts
                   14696:       CODElength  - length of the CODE
                   14697:       IDstart     - column where the student/employee ID starts
                   14698:       IDlength    - length of the student/employee ID info
                   14699:       Qstart      - column where the information from the bubbled
                   14700:                     'questions' start
                   14701:       Qlength     - number of columns comprising a single bubble line from
                   14702:                     the sheet. (usually either 1 or 10)
                   14703:       Qon         - either a single character representing the character used
                   14704:                     to signal a bubble was chosen in the positional setup, or
                   14705:                     the string 'letter' if the letter of the chosen bubble is
                   14706:                     in the final, or 'number' if a number representing the
                   14707:                     chosen bubble is in the file (1->A 0->J)
                   14708:       Qoff        - the character used to represent that a bubble was
                   14709:                     left blank
                   14710:       PaperID     - if the scanning process generates a unique number for each
                   14711:                     sheet scanned the column that this ID number starts in
                   14712:       PaperIDlength - number of columns that comprise the unique ID number
                   14713:                       for the sheet of paper
                   14714:       FirstName   - column that the first name starts in
                   14715:       FirstNameLength - number of columns that the first name spans
                   14716:       LastName    - column that the last name starts in
                   14717:       LastNameLength - number of columns that the last name spans
                   14718:       BubblesPerRow - number of bubbles available in each row used to
                   14719:                       bubble an answer. (If not specified, 10 assumed).
                   14720: 
                   14721: 
                   14722: =item *
                   14723: 
                   14724: get_scantronformat_file($cdom)
                   14725: 
                   14726: $cdom - the course's domain (optional); if not supplied, uses
                   14727: domain for current $env{'request.course.id'}.
                   14728: 
                   14729: Returns an array containing lines from the scantron format file for
                   14730: the domain of the course.
                   14731: 
                   14732: If a url for a custom.tab file is listed in domain's configuration.db,
                   14733: lines are from this file.
                   14734: 
                   14735: Otherwise, if a default.tab has been published in RES space by the
                   14736: domainconfig user, lines are from this file.
                   14737: 
                   14738: Otherwise, fall back to getting lines from the legacy file on the
                   14739: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14740: 
                   14741: =back
                   14742: 
1.243     albertel 14743: =head2 Resource Subroutines
                   14744: 
                   14745: =over 4
1.191     harris41 14746: 
                   14747: =item *
                   14748: 
1.243     albertel 14749: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14750: 
                   14751: =item *
                   14752: 
1.243     albertel 14753: repcopy($filename) : subscribes to the requested file, and attempts to
                   14754: replicate from the owning library server, Might return
1.607     raeburn  14755: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14756: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14757: resource. Expects the local filesystem pathname
                   14758: (/home/httpd/html/res/....)
                   14759: 
                   14760: =back
                   14761: 
                   14762: =head2 Resource Information
                   14763: 
                   14764: =over 4
1.191     harris41 14765: 
                   14766: =item *
                   14767: 
1.1172.2.28  raeburn  14768: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14769: and returns the value of a variety of different possible values,
                   14770: $varname should be a request string, and the other parameters can be
                   14771: used to specify who and what one is asking about. Ordinarily, $cid 
                   14772: does not need to be specified, as it is retrived from 
                   14773: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14774: within lonuserstate::loadmap() when initializing a course, before
                   14775: $env{'request.course.id'} has been set, so it needs to be provided
                   14776: in that one case.
1.243     albertel 14777: 
                   14778: Possible values for $varname are environment.lastname (or other item
                   14779: from the envirnment hash), user.name (or someother aspect about the
                   14780: user), resource.0.maxtries (or some other part and parameter of a
                   14781: resource)
1.204     albertel 14782: 
                   14783: =item *
                   14784: 
1.243     albertel 14785: directcondval($number) : get current value of a condition; reads from a state
                   14786: string
1.204     albertel 14787: 
                   14788: =item *
                   14789: 
1.243     albertel 14790: condval($condidx) : value of condition index based on state
1.204     albertel 14791: 
                   14792: =item *
                   14793: 
1.243     albertel 14794: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14795: resource's metadata, $what should be either a specific key, or either
                   14796: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14797: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14798: 
                   14799: this function automatically caches all requests
1.191     harris41 14800: 
                   14801: =item *
                   14802: 
1.243     albertel 14803: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14804: network of library servers; returns file handle of where SQL and regex results
                   14805: will be stored for query
1.191     harris41 14806: 
                   14807: =item *
                   14808: 
1.1172.2.66  raeburn  14809: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14810: return symbolic list entry (all arguments optional).
                   14811: 
                   14812: Args: filename is the filename (including path) for the file for which a symb
                   14813: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14814: to check access status if more than one resource was found in the bighash
                   14815: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14816: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14817: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14818: cause possible symbs to be checked to determine if they are subject to content
                   14819: blocking, if so they will not be included as possible symbs; possibles is a
                   14820: ref to a hash, which, as a side effect, will be populated with all possible
                   14821: symbs (content blocking not tested).
                   14822: 
1.243     albertel 14823: returns the data handle
1.191     harris41 14824: 
                   14825: =item *
                   14826: 
1.1172.2.17  raeburn  14827: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14828: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14829: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14830: on failure, user must be in a course, as it assumes the existence of
                   14831: the course initial hash, and uses $env('request.course.id'}.  The third
                   14832: arg is an optional reference to a scalar.  If this arg is passed in the
                   14833: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14834: encrypted; otherwise it will be null.
1.243     albertel 14835: 
1.191     harris41 14836: =item *
                   14837: 
1.243     albertel 14838: symbclean($symb) : removes versions numbers from a symb, returns the
                   14839: cleaned symb
1.191     harris41 14840: 
                   14841: =item *
                   14842: 
1.243     albertel 14843: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14844: course map, user must be in a course for it to work.
1.191     harris41 14845: 
                   14846: =item *
                   14847: 
1.243     albertel 14848: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14849: 
                   14850: =item *
                   14851: 
1.243     albertel 14852: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14853: a random seed, all arguments are optional, if they aren't sent it uses the
                   14854: environment to derive them. Note: if symb isn't sent and it can't get one
                   14855: from &symbread it will use the current time as its return value
1.191     harris41 14856: 
                   14857: =item *
                   14858: 
1.243     albertel 14859: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14860: unfakeable, receipt
1.191     harris41 14861: 
                   14862: =item *
                   14863: 
1.620     albertel 14864: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14865: 
                   14866: =item *
                   14867: 
1.243     albertel 14868: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14869: 
                   14870: =item *
                   14871: 
1.243     albertel 14872: 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 14873: 
                   14874: =item *
                   14875: 
1.243     albertel 14876: 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 14877: 
                   14878: =item *
                   14879: 
1.243     albertel 14880: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14881: 
                   14882: =item *
                   14883: 
1.243     albertel 14884: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14885: forcing spreadsheet to reevaluate the resource scores next time.
                   14886: 
1.1172.2.13  raeburn  14887: =item *
                   14888: 
                   14889: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14890: when viewing in course context.
                   14891: 
                   14892:  input: six args -- filename (decluttered), course number, course domain,
                   14893:                     url, symb (if registered) and group (if this is a
                   14894:                     group item -- e.g., bulletin board, group page etc.).
                   14895: 
                   14896:  output: array of five scalars --
                   14897:          $cfile -- url for file editing if editable on current server
                   14898:          $home -- homeserver of resource (i.e., for author if published,
                   14899:                                           or course if uploaded.).
                   14900:          $switchserver --  1 if server switch will be needed.
                   14901:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14902:          $forceview -- 1 if icon/link should be to go to view mode
                   14903: 
                   14904: =item *
                   14905: 
                   14906: is_course_upload($file,$cnum,$cdom)
                   14907: 
                   14908: Used in course context to determine if current file was uploaded to
                   14909: the course (i.e., would be found in /userfiles/docs on the course's
                   14910: homeserver.
                   14911: 
                   14912:   input: 3 args -- filename (decluttered), course number and course domain.
                   14913:   output: boolean -- 1 if file was uploaded.
                   14914: 
1.243     albertel 14915: =back
                   14916: 
                   14917: =head2 Storing/Retreiving Data
                   14918: 
                   14919: =over 4
1.191     harris41 14920: 
                   14921: =item *
                   14922: 
1.1172.2.64  raeburn  14923: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14924: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14925: the remaining args aren't required and if they aren't passed or are '' they will
                   14926: be derived from the env (with the exception of $laststore, which is an
                   14927: optional arg used when a user's submission is stored in grading).
                   14928: $laststore is $version=$timestamp, where $version is the most recent version
                   14929: number retrieved for the corresponding $symb in the $namespace db file, and
                   14930: $timestamp is the timestamp for that transaction (UNIX time).
                   14931: $laststore is currently only passed when cstore() is called by
                   14932: structuretags::finalize_storage().
1.191     harris41 14933: 
                   14934: =item *
                   14935: 
1.1172.2.64  raeburn  14936: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14937: but uses critical subroutine
1.191     harris41 14938: 
                   14939: =item *
                   14940: 
1.243     albertel 14941: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14942: all args are optional
1.191     harris41 14943: 
                   14944: =item *
                   14945: 
1.717     albertel 14946: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14947: dumps the complete (or key matching regexp) namespace into a hash
                   14948: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14949: normally &store()ed into
                   14950: 
                   14951: $range should be either an integer '100' (give me the first 100
                   14952:                                            matching records)
                   14953:               or be  two integers sperated by a - with no spaces
                   14954:                  '30-50' (give me the 30th through the 50th matching
                   14955:                           records)
                   14956: 
                   14957: 
                   14958: =item *
                   14959: 
1.1172.2.59  raeburn  14960: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14961: replaces a &store() version of data with a replacement set of data
                   14962: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14963: reference. If $tolog is true, the transaction is logged in the courselog
                   14964: with an action=PUTSTORE.
1.717     albertel 14965: 
                   14966: =item *
                   14967: 
1.243     albertel 14968: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14969: works very similar to store/cstore, but all data is stored in a
                   14970: temporary location and can be reset using tmpreset, $storehash should
                   14971: be a hash reference, returns nothing on success
1.191     harris41 14972: 
                   14973: =item *
                   14974: 
1.243     albertel 14975: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14976: similar to restore, but all data is stored in a temporary location and
                   14977: can be reset using tmpreset. Returns a hash of values on success,
                   14978: error string otherwise.
1.191     harris41 14979: 
                   14980: =item *
                   14981: 
1.243     albertel 14982: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14983: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14984: 
                   14985: =item *
                   14986: 
1.243     albertel 14987: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14988: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14989: 
                   14990: =item *
                   14991: 
1.243     albertel 14992: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14993: namesp ($udom and $uname are optional)
1.191     harris41 14994: 
                   14995: =item *
                   14996: 
1.702     albertel 14997: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14998: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14999: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15000: 
1.702     albertel 15001: $range should be either an integer '100' (give me the first 100
                   15002:                                            matching records)
                   15003:               or be  two integers sperated by a - with no spaces
                   15004:                  '30-50' (give me the 30th through the 50th matching
                   15005:                           records)
1.449     matthew  15006: =item *
                   15007: 
                   15008: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15009: $store can be a scalar, an array reference, or if the amount to be 
                   15010: incremented is > 1, a hash reference.
                   15011: 
                   15012: ($udom and $uname are optional)
1.191     harris41 15013: 
                   15014: =item *
                   15015: 
1.243     albertel 15016: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15017: ($udom and $uname are optional)
1.191     harris41 15018: 
                   15019: =item *
                   15020: 
1.243     albertel 15021: cput($namespace,$storehash,$udom,$uname) : critical put
                   15022: ($udom and $uname are optional)
1.191     harris41 15023: 
                   15024: =item *
                   15025: 
1.748     albertel 15026: newput($namespace,$storehash,$udom,$uname) :
                   15027: 
                   15028: Attempts to store the items in the $storehash, but only if they don't
                   15029: currently exist, if this succeeds you can be certain that you have 
                   15030: successfully created a new key value pair in the $namespace db.
                   15031: 
                   15032: 
                   15033: Args:
                   15034:  $namespace: name of database to store values to
                   15035:  $storehash: hashref to store to the db
                   15036:  $udom: (optional) domain of user containing the db
                   15037:  $uname: (optional) name of user caontaining the db
                   15038: 
                   15039: Returns:
                   15040:  'ok' -> succeeded in storing all keys of $storehash
                   15041:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15042:                         least <key> already existed in the db (other
                   15043:                         requested keys may also already exist)
1.967     bisitz   15044:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15045:  'con_lost' -> unable to contact request server
                   15046:  'refused' -> action was not allowed by remote machine
                   15047: 
                   15048: 
                   15049: =item *
                   15050: 
1.243     albertel 15051: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15052: reference filled in from namesp (encrypts the return communication)
                   15053: ($udom and $uname are optional)
1.191     harris41 15054: 
                   15055: =item *
                   15056: 
1.243     albertel 15057: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15058: critical subroutine
                   15059: 
1.806     raeburn  15060: =item *
                   15061: 
1.860     raeburn  15062: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15063: array reference filled in from namespace found in domain level on either
                   15064: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15065: 
                   15066: =item *
                   15067: 
1.860     raeburn  15068: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15069: domain level either on specified domain server ($uhome) or primary domain 
                   15070: server ($udom and $uhome are optional)
1.806     raeburn  15071: 
1.943     raeburn  15072: =item * 
                   15073: 
1.1172.2.35  raeburn  15074: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15075: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15076: the target domain.
                   15077: 
                   15078: May also include additional key => value pairs for the following groups:
                   15079: 
                   15080: =over
                   15081: 
                   15082: =item
                   15083: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15084: 
                   15085: =over
                   15086: 
                   15087: =item defaultquota, authorquota
                   15088: 
                   15089: =back
                   15090: 
                   15091: =item
                   15092: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15093: portfolio for users).
                   15094: 
                   15095: =over
                   15096: 
                   15097: =item
                   15098: aboutme, blog, webdav, portfolio
                   15099: 
                   15100: =back
                   15101: 
                   15102: =item
                   15103: requestcourses: ability to request courses, and how requests are processed.
                   15104: 
                   15105: =over
                   15106: 
                   15107: =item
1.1172.2.37  raeburn  15108: official, unofficial, community, textbook
1.1172.2.35  raeburn  15109: 
                   15110: =back
                   15111: 
                   15112: =item
                   15113: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15114: 
                   15115: =over
                   15116: 
                   15117: =item
1.1172.2.44  raeburn  15118: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15119: 
                   15120: =back
                   15121: 
                   15122: =item
                   15123: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15124: for course's uploaded content.
                   15125: 
                   15126: =over
                   15127: 
                   15128: =item
1.1172.2.68  raeburn  15129: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15130: communityquota, textbookquota
1.1172.2.35  raeburn  15131: 
                   15132: =back
                   15133: 
                   15134: =item
                   15135: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15136: on your servers.
                   15137: 
                   15138: =over
                   15139: 
                   15140: =item
                   15141: remotesessions, hostedsessions
                   15142: 
                   15143: =back
                   15144: 
                   15145: =back
                   15146: 
                   15147: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15148: utility to create a configuration.db file on a domain's primary library server
                   15149: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15150: -- corresponding values are authentication type (internal, krb4, krb5,
                   15151: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15152: will be available. Values are retrieved from cache (if current), unless the
                   15153: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15154: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15155: 
                   15156: Typical usage:
1.943     raeburn  15157: 
1.1172.2.35  raeburn  15158: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15159: 
1.243     albertel 15160: =back
                   15161: 
                   15162: =head2 Network Status Functions
                   15163: 
                   15164: =over 4
1.191     harris41 15165: 
                   15166: =item *
                   15167: 
1.1137    raeburn  15168: dirlist() : return directory list based on URI (first arg).
                   15169: 
                   15170: Inputs: 1 required, 5 optional.
                   15171: 
                   15172: =over
                   15173: 
                   15174: =item 
                   15175: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15176: 
                   15177: =item
                   15178: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15179: 
                   15180: =item
                   15181: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15182: 
                   15183: =item
                   15184: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15185: 
                   15186: =item
                   15187: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15188: 
                   15189: =item 
                   15190: $alternateRoot - path to prepend in place of path from $uri.
                   15191: 
                   15192: =back
                   15193: 
                   15194: Returns: Array of up to two items.
                   15195: 
                   15196: =over
                   15197: 
                   15198: a reference to an array of files/subdirectories
                   15199: 
                   15200: =over
                   15201: 
                   15202: Each element in the array of files/subdirectories is a & separated list of
                   15203: item name and the result of running stat on the item.  If dirlist was requested
                   15204: for a file instead of a directory, the item name will be ''. For a directory 
                   15205: listing, if the item is a metadata file, the element will end &N&M 
                   15206: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15207: default copyright set (1).  
                   15208: 
                   15209: =back
                   15210: 
                   15211: a scalar containing error condition (if encountered).
                   15212: 
                   15213: =over
                   15214: 
                   15215: =item 
                   15216: no_host (no homeserver identified for $username:$domain).
                   15217: 
                   15218: =item 
                   15219: no_such_host (server contacted for listing not identified as valid host).
                   15220: 
                   15221: =item 
                   15222: con_lost (connection to remote server failed).
                   15223: 
                   15224: =item 
                   15225: refused (invalid $username:$domain received on lond side).
                   15226: 
                   15227: =item 
                   15228: no_such_dir (directory at specified path on lond side does not exist). 
                   15229: 
                   15230: =item 
                   15231: empty (directory at specified path on lond side is empty).
                   15232: 
                   15233: =over
                   15234: 
                   15235: This is currently not encountered because the &ls3, &ls2, 
                   15236: &ls (_handler) routines on the lond side do not filter out
                   15237: . and .. from a directory listing. 
                   15238: 
                   15239: =back
                   15240: 
                   15241: =back
                   15242: 
                   15243: =back
1.191     harris41 15244: 
                   15245: =item *
                   15246: 
1.243     albertel 15247: spareserver() : find server with least workload from spare.tab
                   15248: 
1.986     foxr     15249: 
                   15250: =item *
                   15251: 
                   15252: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15253: if there is no corresponding loncapa host.
                   15254: 
1.243     albertel 15255: =back
                   15256: 
1.986     foxr     15257: 
1.243     albertel 15258: =head2 Apache Request
                   15259: 
                   15260: =over 4
1.191     harris41 15261: 
                   15262: =item *
                   15263: 
1.243     albertel 15264: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15265: localhost, posts hash
                   15266: 
                   15267: =back
                   15268: 
                   15269: =head2 Data to String to Data
                   15270: 
                   15271: =over 4
1.191     harris41 15272: 
                   15273: =item *
                   15274: 
1.243     albertel 15275: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15276: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15277: 
                   15278: =item *
                   15279: 
1.243     albertel 15280: hashref2str($hashref) : convert a hashref into a string complete with
                   15281: escaping and '=' and '&' separators, supports elements that are
                   15282: arrayrefs and hashrefs
1.191     harris41 15283: 
                   15284: =item *
                   15285: 
1.243     albertel 15286: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15287: with escaping and '&' separators, supports elements that are arrayrefs
                   15288: and hashrefs
1.191     harris41 15289: 
                   15290: =item *
                   15291: 
1.243     albertel 15292: str2hash($string) : convert string to hash using unescaping and
                   15293: splitting on '=' and '&', supports elements that are arrayrefs and
                   15294: hashrefs
1.191     harris41 15295: 
                   15296: =item *
                   15297: 
1.243     albertel 15298: str2array($string) : convert string to hash using unescaping and
                   15299: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15300: 
                   15301: =back
                   15302: 
                   15303: =head2 Logging Routines
                   15304: 
                   15305: 
                   15306: These routines allow one to make log messages in the lonnet.log and
                   15307: lonnet.perm logfiles.
1.191     harris41 15308: 
1.1119    foxr     15309: =over 4
                   15310: 
1.191     harris41 15311: =item *
                   15312: 
1.243     albertel 15313: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15314: 
                   15315: =item *
                   15316: 
1.243     albertel 15317: logthis() : append message to the normal lonnet.log file, it gets
                   15318: preiodically rolled over and deleted.
1.191     harris41 15319: 
                   15320: =item *
                   15321: 
1.243     albertel 15322: logperm() : append a permanent message to lonnet.perm.log, this log
                   15323: file never gets deleted by any automated portion of the system, only
                   15324: messages of critical importance should go in here.
                   15325: 
1.1119    foxr     15326: 
1.243     albertel 15327: =back
                   15328: 
                   15329: =head2 General File Helper Routines
                   15330: 
                   15331: =over 4
1.191     harris41 15332: 
                   15333: =item *
                   15334: 
1.481     raeburn  15335: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15336: (a) files in /uploaded
                   15337:   (i) If a local copy of the file exists - 
                   15338:       compares modification date of local copy with last-modified date for 
                   15339:       definitive version stored on home server for course. If local copy is 
                   15340:       stale, requests a new version from the home server and stores it. 
                   15341:       If the original has been removed from the home server, then local copy 
                   15342:       is unlinked.
                   15343:   (ii) If local copy does not exist -
                   15344:       requests the file from the home server and stores it. 
                   15345:   
                   15346:   If $caller is 'uploadrep':  
                   15347:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15348:     for request for files originally uploaded via DOCS. 
                   15349:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15350:   
                   15351:   Otherwise:
                   15352:      This indicates a call from the content generation phase of the request.
                   15353:      -  returns the entire contents of the file or -1.
                   15354:      
                   15355: (b) files in /res
                   15356:    - returns the entire contents of a file or -1; 
                   15357:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15358: 
1.712     albertel 15359: 
                   15360: =item *
                   15361: 
                   15362: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15363:                   reference
                   15364: 
                   15365: returns either a stat() list of data about the file or an empty list
                   15366: if the file doesn't exist or couldn't find out about it (connection
                   15367: problems or user unknown)
                   15368: 
1.191     harris41 15369: =item *
                   15370: 
1.243     albertel 15371: filelocation($dir,$file) : returns file system location of a file
                   15372: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15373: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15374: and a file of ../bob will become /a/bob)
1.191     harris41 15375: 
                   15376: =item *
                   15377: 
                   15378: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15379: filelocation except for hrefs
                   15380: 
                   15381: =item *
                   15382: 
1.1172.2.49  raeburn  15383: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15384: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15385: 
1.243     albertel 15386: =back
                   15387: 
1.608     albertel 15388: =head2 Usererfile file routines (/uploaded*)
                   15389: 
                   15390: =over 4
                   15391: 
                   15392: =item *
                   15393: 
                   15394: userfileupload(): main rotine for putting a file in a user or course's
                   15395:                   filespace, arguments are,
                   15396: 
1.620     albertel 15397:  formname - required - this is the name of the element in $env where the
1.608     albertel 15398:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15399:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15400:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15401:  context - if coursedoc, store the file in the course of the active role
                   15402:              of the current user; 
                   15403:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15404:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15405:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15406:          if undefined, it will be placed in "unknown"
                   15407: 
                   15408:  (This routine calls clean_filename() to remove any dangerous
                   15409:  characters from the filename, and then calls finuserfileupload() to
                   15410:  complete the transaction)
                   15411: 
                   15412:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15413:  and /adm/notfound.html if unsuccessful
                   15414: 
                   15415: =item *
                   15416: 
                   15417: clean_filename(): routine for cleaing a filename up for storage in
                   15418:                  userfile space, argument is:
                   15419: 
                   15420:  filename - proposed filename
                   15421: 
                   15422: returns: the new clean filename
                   15423: 
                   15424: =item *
                   15425: 
1.1090    raeburn  15426: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15427: userspace, probably shouldn't be called directly
                   15428: 
                   15429:   docuname: username or courseid of destination for the file
                   15430:   docudom: domain of user/course of destination for the file
                   15431:   formname: same as for userfileupload()
1.1090    raeburn  15432:   fname: filename (including subdirectories) for the file
                   15433:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15434:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15435:   allfiles: reference to hash used to store objects found by parser
                   15436:   codebase: reference to hash used for codebases of java objects found by parser
                   15437:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15438:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15439:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15440:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15441:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15442:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15443:   mimetype: reference to scalar to accommodate mime type determined
                   15444:             from File::MMagic if $parser = parse.
1.608     albertel 15445: 
                   15446:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15447:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15448:  was 'overwrite').
                   15449:  
1.608     albertel 15450: 
                   15451: =item *
                   15452: 
                   15453: renameuserfile(): renames an existing userfile to a new name
                   15454: 
                   15455:   Args:
                   15456:    docuname: username or courseid of destination for the file
                   15457:    docudom: domain of user/course of destination for the file
                   15458:    old: current file name (including any subdirs under userfiles)
                   15459:    new: desired file name (including any subdirs under userfiles)
                   15460: 
                   15461: =item *
                   15462: 
                   15463: mkdiruserfile(): creates a directory is a userfiles dir
                   15464: 
                   15465:   Args:
                   15466:    docuname: username or courseid of destination for the file
                   15467:    docudom: domain of user/course of destination for the file
                   15468:    dir: dir to create (including any subdirs under userfiles)
                   15469: 
                   15470: =item *
                   15471: 
                   15472: removeuserfile(): removes a file that exists in userfiles
                   15473: 
                   15474:   Args:
                   15475:    docuname: username or courseid of destination for the file
                   15476:    docudom: domain of user/course of destination for the file
                   15477:    fname: filname to delete (including any subdirs under userfiles)
                   15478: 
                   15479: =item *
                   15480: 
                   15481: removeuploadedurl(): convience function for removeuserfile()
                   15482: 
                   15483:   Args:
                   15484:    url:  a full /uploaded/... url to delete
                   15485: 
1.747     albertel 15486: =item * 
                   15487: 
                   15488: get_portfile_permissions():
                   15489:   Args:
                   15490:     domain: domain of user or course contain the portfolio files
                   15491:     user: name of user or num of course contain the portfolio files
                   15492:   Returns:
                   15493:     hashref of a dump of the proper file_permissions.db
                   15494:    
                   15495: 
                   15496: =item * 
                   15497: 
                   15498: get_access_controls():
                   15499: 
                   15500: Args:
                   15501:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15502:   group: (optional) the group you want the files associated with
                   15503:   file: (optional) the file you want access info on
                   15504: 
                   15505: Returns:
1.749     raeburn  15506:     a hash (keys are file names) of hashes containing
                   15507:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15508:         values are XML containing access control settings (see below) 
1.747     albertel 15509: 
                   15510: Internal notes:
                   15511: 
1.749     raeburn  15512:  access controls are stored in file_permissions.db as key=value pairs.
                   15513:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15514:         where scope -> public,guest,course,group,domains or users.
                   15515:               end -> UNIX time for end of access (0 -> no end date)
                   15516:               start -> UNIX time for start of access
                   15517: 
                   15518:     value -> XML description of access control
                   15519:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15520:             <start></start>
                   15521:             <end></end>
                   15522: 
                   15523:             <password></password>  for scope type = guest
                   15524: 
                   15525:             <domain></domain>     for scope type = course or group
                   15526:             <number></number>
                   15527:             <roles id="">
                   15528:              <role></role>
                   15529:              <access></access>
                   15530:              <section></section>
                   15531:              <group></group>
                   15532:             </roles>
                   15533: 
                   15534:             <dom></dom>         for scope type = domains
                   15535: 
                   15536:             <users>             for scope type = users
                   15537:              <user>
                   15538:               <uname></uname>
                   15539:               <udom></udom>
                   15540:              </user>
                   15541:             </users>
                   15542:            </scope> 
                   15543:               
                   15544:  Access data is also aggregated for each file in an additional key=value pair:
                   15545:  key -> path to file/file_name\0accesscontrol 
                   15546:  value -> reference to hash
                   15547:           hash contains key = value pairs
                   15548:           where key = uniqueID:scope_end_start
                   15549:                 value = UNIX time record was last updated
                   15550: 
                   15551:           Used to improve speed of look-ups of access controls for each file.  
                   15552:  
                   15553:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15554: 
1.1172.2.13  raeburn  15555: =item *
                   15556: 
1.749     raeburn  15557: modify_access_controls():
                   15558: 
                   15559: Modifies access controls for a portfolio file
                   15560: Args
                   15561: 1. file name
                   15562: 2. reference to hash of required changes,
                   15563: 3. domain
                   15564: 4. username
                   15565:   where domain,username are the domain of the portfolio owner 
                   15566:   (either a user or a course) 
                   15567: 
                   15568: Returns:
                   15569: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15570: 2. result of deletions ('ok' or 'error', with error message).
                   15571: 3. reference to hash of any new or updated access controls.
                   15572: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15573:    key = integer (inbound ID)
1.1172.2.13  raeburn  15574:    value = uniqueID
                   15575: 
                   15576: =item *
                   15577: 
                   15578: get_timebased_id():
                   15579: 
                   15580: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15581: course via the Course Editor (e.g., folders, composite pages,
                   15582: group bulletin boards).
                   15583: 
                   15584: Args: (first three required; six others optional)
                   15585: 
                   15586: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15587:    docssequence, or name of group
                   15588: 
                   15589: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15590:    e.g., num, boardids
                   15591: 
                   15592: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15593:    file will be named nohist_namespace.db
                   15594: 
                   15595: 4. cdom: domain of course; default is current course domain from %env
                   15596: 
                   15597: 5. cnum: course number; default is current course number from %env
                   15598: 
                   15599: 6. idtype: set to concat if an additional digit is to be appended to the
                   15600:    unix timestamp to form the suffix, if the plain timestamp is already
                   15601:    in use.  Default is to not do this, but simply increment the unix
                   15602:    timestamp by 1 until a unique key is obtained.
                   15603: 
                   15604: 7. who: holder of locking key; defaults to user:domain for user.
                   15605: 
                   15606: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15607:    retrying); default is 3.
                   15608: 
                   15609: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15610: 
                   15611: Returns:
                   15612: 
                   15613: 1. suffix obtained (numeric)
                   15614: 
                   15615: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15616: 
                   15617: 3. error: contains (localized) error message if an error occurred.
                   15618: 
1.747     albertel 15619: 
1.608     albertel 15620: =back
                   15621: 
1.243     albertel 15622: =head2 HTTP Helper Routines
                   15623: 
                   15624: =over 4
                   15625: 
1.191     harris41 15626: =item *
                   15627: 
                   15628: escape() : unpack non-word characters into CGI-compatible hex codes
                   15629: 
                   15630: =item *
                   15631: 
                   15632: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15633: 
1.243     albertel 15634: =back
                   15635: 
                   15636: =head1 PRIVATE SUBROUTINES
                   15637: 
                   15638: =head2 Underlying communication routines (Shouldn't call)
                   15639: 
                   15640: =over 4
                   15641: 
                   15642: =item *
                   15643: 
                   15644: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15645: 
                   15646: =item *
                   15647: 
                   15648: reply() : uses subreply to send a message to remote machine, logs all failures
                   15649: 
                   15650: =item *
                   15651: 
                   15652: critical() : passes a critical message to another server; if cannot
                   15653: get through then place message in connection buffer directory and
                   15654: returns con_delayed, if incapable of saving message, returns
                   15655: con_failed
                   15656: 
                   15657: =item *
                   15658: 
                   15659: reconlonc() : tries to reconnect lonc client processes.
                   15660: 
                   15661: =back
                   15662: 
                   15663: =head2 Resource Access Logging
                   15664: 
                   15665: =over 4
                   15666: 
                   15667: =item *
                   15668: 
                   15669: flushcourselogs() : flush (save) buffer logs and access logs
                   15670: 
                   15671: =item *
                   15672: 
                   15673: courselog($what) : save message for course in hash
                   15674: 
                   15675: =item *
                   15676: 
                   15677: courseacclog($what) : save message for course using &courselog().  Perform
                   15678: special processing for specific resource types (problems, exams, quizzes, etc).
                   15679: 
1.191     harris41 15680: =item *
                   15681: 
                   15682: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15683: as a PerlChildExitHandler
1.243     albertel 15684: 
                   15685: =back
                   15686: 
                   15687: =head2 Other
                   15688: 
                   15689: =over 4
                   15690: 
                   15691: =item *
                   15692: 
                   15693: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15694: 
                   15695: =back
                   15696: 
                   15697: =cut
1.877     foxr     15698: 

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