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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .2(raebu    4:20): # $Id: lonnet.pm,v 1.1172.2.118.2.1 2020/01/17 16:49:28 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.1172.2.118.  .1(raebu 1853:20):         my $rep;
                   1854:20):         if ($namespace =~ /^enc/) {
                   1855:20):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1856:20):         } else {
                   1857:20):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1858:20):         }
1.866     raeburn  1859:         my %returnhash;
1.875     albertel 1860:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1861:             return %returnhash;
                   1862:         }
1.806     raeburn  1863:         my @pairs=split(/\&/,$rep);
                   1864:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1865:             return @pairs;
                   1866:         }
                   1867:         my $i=0;
                   1868:         foreach my $item (@$storearr) {
                   1869:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1870:             $i++;
                   1871:         }
                   1872:         return %returnhash;
                   1873:     } else {
1.880     banghart 1874:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1875:     }
                   1876: }
                   1877: 
                   1878: # -------------------------------------------- put items in domain db files 
                   1879: 
                   1880: sub put_dom {
1.860     raeburn  1881:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1882:     if (!$udom) {
                   1883:         $udom=$env{'user.domain'};
                   1884:         if (defined(&domain($udom,'primary'))) {
                   1885:             $uhome=&domain($udom,'primary');
                   1886:         } else {
1.874     albertel 1887:             undef($uhome);
1.860     raeburn  1888:         }
                   1889:     } else {
                   1890:         if (!$uhome) {
                   1891:             if (defined(&domain($udom,'primary'))) {
                   1892:                 $uhome=&domain($udom,'primary');
                   1893:             }
                   1894:         }
                   1895:     } 
                   1896:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1897:         my $items='';
                   1898:         foreach my $item (keys(%$storehash)) {
                   1899:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1900:         }
                   1901:         $items=~s/\&$//;
1.1172.2.118.  .1(raebu 1902:20):         if ($namespace =~ /^enc/) {
                   1903:20):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1904:20):         } else {
                   1905:20):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1906:20):         }
1.806     raeburn  1907:     } else {
1.860     raeburn  1908:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1909:     }
                   1910: }
                   1911: 
1.1023    raeburn  1912: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1913: sub newput_dom {
1.1023    raeburn  1914:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1915:     my $result;
                   1916:     if (!$udom) {
                   1917:         $udom=$env{'user.domain'};
                   1918:     }
1.1023    raeburn  1919:     if ($udom) {
                   1920:         my $uname = &get_domainconfiguser($udom);
                   1921:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1922:     }
                   1923:     return $result;
                   1924: }
                   1925: 
1.1023    raeburn  1926: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1927: sub del_dom {
1.1023    raeburn  1928:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1929:     if (ref($storearr) eq 'ARRAY') {
                   1930:         if (!$udom) {
                   1931:             $udom=$env{'user.domain'};
                   1932:         }
1.1023    raeburn  1933:         if ($udom) {
                   1934:             my $uname = &get_domainconfiguser($udom); 
                   1935:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1936:         }
                   1937:     }
                   1938: }
                   1939: 
1.1023    raeburn  1940: # ----------------------------------construct domainconfig user for a domain 
                   1941: sub get_domainconfiguser {
                   1942:     my ($udom) = @_;
                   1943:     return $udom.'-domainconfig';
                   1944: }
                   1945: 
1.837     raeburn  1946: sub retrieve_inst_usertypes {
                   1947:     my ($udom) = @_;
                   1948:     my (%returnhash,@order);
1.989     raeburn  1949:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1950:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1951:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1952:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1953:     } else {
                   1954:         if (defined(&domain($udom,'primary'))) {
                   1955:             my $uhome=&domain($udom,'primary');
                   1956:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1957:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1958:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1959:                 return (\%returnhash,\@order);
                   1960:             }
                   1961:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1962:             my @pairs=split(/\&/,$hashitems);
                   1963:             foreach my $item (@pairs) {
                   1964:                 my ($key,$value)=split(/=/,$item,2);
                   1965:                 $key = &unescape($key);
                   1966:                 next if ($key =~ /^error: 2 /);
                   1967:                 $returnhash{$key}=&thaw_unescape($value);
                   1968:             }
                   1969:             my @esc_order = split(/\&/,$orderitems);
                   1970:             foreach my $item (@esc_order) {
                   1971:                 push(@order,&unescape($item));
                   1972:             }
                   1973:         } else {
1.1172.2.44  raeburn  1974:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1975:         }
1.1172.2.44  raeburn  1976:         return (\%returnhash,\@order);
1.837     raeburn  1977:     }
                   1978: }
                   1979: 
1.868     raeburn  1980: sub is_domainimage {
                   1981:     my ($url) = @_;
1.1172.2.74  raeburn  1982:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1983:         if (&domain($1) ne '') {
                   1984:             return '1';
                   1985:         }
                   1986:     }
                   1987:     return;
                   1988: }
                   1989: 
1.899     raeburn  1990: sub inst_directory_query {
                   1991:     my ($srch) = @_;
                   1992:     my $udom = $srch->{'srchdomain'};
                   1993:     my %results;
                   1994:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1995:     my $outcome;
1.899     raeburn  1996:     if ($homeserver ne '') {
1.1172.2.116  raeburn  1997:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   1998:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  1999:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2000:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2001:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2002:                     (($major == 2) && ($minor < 11)) ||
                   2003:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2004:                     return;
                   2005:                 }
                   2006:             }
                   2007:         }
1.904     albertel 2008: 	my $queryid=&reply("querysend:instdirsearch:".
                   2009: 			   &escape($srch->{'srchby'}).':'.
                   2010: 			   &escape($srch->{'srchterm'}).':'.
                   2011: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2012: 	my $host=&hostname($homeserver);
                   2013: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2014: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2015: 	    return;
                   2016: 	}
                   2017: 	my $response = &get_query_reply($queryid);
                   2018: 	my $maxtries = 5;
                   2019: 	my $tries = 1;
                   2020: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2021: 	    $response = &get_query_reply($queryid);
                   2022: 	    $tries ++;
                   2023: 	}
                   2024: 
                   2025:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2026:             if ($response eq 'unavailable') {
                   2027:                 $outcome = $response;
                   2028:             } else {
                   2029:                 $outcome = 'ok';
                   2030:                 my @matches = split(/\n/,$response);
                   2031:                 foreach my $match (@matches) {
                   2032:                     my ($key,$value) = split(/=/,$match);
                   2033:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2034:                 }
1.899     raeburn  2035:             }
                   2036:         }
                   2037:     }
1.909     raeburn  2038:     return ($outcome,%results);
1.899     raeburn  2039: }
                   2040: 
                   2041: sub usersearch {
                   2042:     my ($srch) = @_;
                   2043:     my $dom = $srch->{'srchdomain'};
                   2044:     my %results;
                   2045:     my %libserv = &all_library();
                   2046:     my $query = 'usersearch';
                   2047:     foreach my $tryserver (keys(%libserv)) {
                   2048:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2049:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2050:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2051:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118.  .2(raebu 2052:20):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2053:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2054:                              (($major == 2) && ($minor < 11)) ||
                   2055:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2056:                 }
                   2057:             }
1.899     raeburn  2058:             my $host=&hostname($tryserver);
                   2059:             my $queryid=
1.911     raeburn  2060:                 &reply("querysend:".&escape($query).':'.
                   2061:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2062:                        &escape($srch->{'srchtype'}).':'.
                   2063:                        &escape($srch->{'srchterm'}),$tryserver);
                   2064:             if ($queryid !~/^\Q$host\E\_/) {
                   2065:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2066:                 next;
1.899     raeburn  2067:             }
                   2068:             my $reply = &get_query_reply($queryid);
                   2069:             my $maxtries = 1;
                   2070:             my $tries = 1;
                   2071:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2072:                 $reply = &get_query_reply($queryid);
                   2073:                 $tries ++;
                   2074:             }
                   2075:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2076:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2077:             } else {
1.911     raeburn  2078:                 my @matches;
                   2079:                 if ($reply =~ /\n/) {
                   2080:                     @matches = split(/\n/,$reply);
                   2081:                 } else {
                   2082:                     @matches = split(/\&/,$reply);
                   2083:                 }
1.899     raeburn  2084:                 foreach my $match (@matches) {
                   2085:                     my ($uname,$udom,%userhash);
1.911     raeburn  2086:                     foreach my $entry (split(/:/,$match)) {
                   2087:                         my ($key,$value) =
                   2088:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2089:                         $userhash{$key} = $value;
                   2090:                         if ($key eq 'username') {
                   2091:                             $uname = $value;
                   2092:                         } elsif ($key eq 'domain') {
                   2093:                             $udom = $value;
1.911     raeburn  2094:                         }
1.899     raeburn  2095:                     }
                   2096:                     $results{$uname.':'.$udom} = \%userhash;
                   2097:                 }
                   2098:             }
                   2099:         }
                   2100:     }
                   2101:     return %results;
                   2102: }
                   2103: 
1.912     raeburn  2104: sub get_instuser {
                   2105:     my ($udom,$uname,$id) = @_;
                   2106:     my $homeserver = &domain($udom,'primary');
                   2107:     my ($outcome,%results);
                   2108:     if ($homeserver ne '') {
                   2109:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2110:                            &escape($id).':'.&escape($udom),$homeserver);
                   2111:         my $host=&hostname($homeserver);
                   2112:         if ($queryid !~/^\Q$host\E\_/) {
                   2113:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2114:             return;
                   2115:         }
                   2116:         my $response = &get_query_reply($queryid);
                   2117:         my $maxtries = 5;
                   2118:         my $tries = 1;
                   2119:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2120:             $response = &get_query_reply($queryid);
                   2121:             $tries ++;
                   2122:         }
                   2123:         if (!&error($response) && $response ne 'refused') {
                   2124:             if ($response eq 'unavailable') {
                   2125:                 $outcome = $response;
                   2126:             } else {
                   2127:                 $outcome = 'ok';
                   2128:                 my @matches = split(/\n/,$response);
                   2129:                 foreach my $match (@matches) {
                   2130:                     my ($key,$value) = split(/=/,$match);
                   2131:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2132:                 }
                   2133:             }
                   2134:         }
                   2135:     }
                   2136:     my %userinfo;
                   2137:     if (ref($results{$uname}) eq 'HASH') {
                   2138:         %userinfo = %{$results{$uname}};
                   2139:     } 
                   2140:     return ($outcome,%userinfo);
                   2141: }
                   2142: 
1.1172.2.69  raeburn  2143: sub get_multiple_instusers {
                   2144:     my ($udom,$users,$caller) = @_;
                   2145:     my ($outcome,$results);
                   2146:     if (ref($users) eq 'HASH') {
                   2147:         my $count = keys(%{$users});
                   2148:         my $requested = &freeze_escape($users);
                   2149:         my $homeserver = &domain($udom,'primary');
                   2150:         if ($homeserver ne '') {
                   2151:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2152:             my $host=&hostname($homeserver);
                   2153:             if ($queryid !~/^\Q$host\E\_/) {
                   2154:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2155:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2156:                 return ($outcome,$results);
                   2157:             }
                   2158:             my $response = &get_query_reply($queryid);
                   2159:             my $maxtries = 5;
                   2160:             if ($count > 100) {
                   2161:                 $maxtries = 1+int($count/20);
                   2162:             }
                   2163:             my $tries = 1;
                   2164:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2165:                 $response = &get_query_reply($queryid);
                   2166:                 $tries ++;
                   2167:             }
                   2168:             if ($response eq '') {
                   2169:                 $results = {};
                   2170:                 foreach my $key (keys(%{$users})) {
                   2171:                     my ($uname,$id);
                   2172:                     if ($caller eq 'id') {
                   2173:                         $id = $key;
                   2174:                     } else {
                   2175:                         $uname = $key;
                   2176:                     }
                   2177:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2178:                     $outcome = $resp;
                   2179:                     if ($resp eq 'ok') {
                   2180:                         %{$results} = (%{$results}, %info);
                   2181:                     } else {
                   2182:                         last;
                   2183:                     }
                   2184:                 }
                   2185:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2186:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2187:                     $outcome = $response;
                   2188:                 } else {
                   2189:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2190:                     if ($outcome eq 'ok') {
                   2191:                         $results = &thaw_unescape($userdata);
                   2192:                     }
                   2193:                 }
                   2194:             }
                   2195:         }
                   2196:     }
                   2197:     return ($outcome,$results);
                   2198: }
                   2199: 
1.912     raeburn  2200: sub inst_rulecheck {
1.923     raeburn  2201:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2202:     my %returnhash;
                   2203:     if ($udom ne '') {
                   2204:         if (ref($rules) eq 'ARRAY') {
                   2205:             @{$rules} = map {&escape($_);} (@{$rules});
                   2206:             my $rulestr = join(':',@{$rules});
                   2207:             my $homeserver=&domain($udom,'primary');
                   2208:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2209:                 my $response;
                   2210:                 if ($item eq 'username') {                
                   2211:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2212:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2213:                                               $homeserver));
1.923     raeburn  2214:                 } elsif ($item eq 'id') {
                   2215:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2216:                                               ':'.&escape($id).':'.$rulestr,
                   2217:                                               $homeserver));
1.945     raeburn  2218:                 } elsif ($item eq 'selfcreate') {
                   2219:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2220:                                                &escape($udom).':'.&escape($uname).
                   2221:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2222:                 }
1.912     raeburn  2223:                 if ($response ne 'refused') {
                   2224:                     my @pairs=split(/\&/,$response);
                   2225:                     foreach my $item (@pairs) {
                   2226:                         my ($key,$value)=split(/=/,$item,2);
                   2227:                         $key = &unescape($key);
                   2228:                         next if ($key =~ /^error: 2 /);
                   2229:                         $returnhash{$key}=&thaw_unescape($value);
                   2230:                     }
                   2231:                 }
                   2232:             }
                   2233:         }
                   2234:     }
                   2235:     return %returnhash;
                   2236: }
                   2237: 
                   2238: sub inst_userrules {
1.923     raeburn  2239:     my ($udom,$check) = @_;
1.912     raeburn  2240:     my (%ruleshash,@ruleorder);
                   2241:     if ($udom ne '') {
                   2242:         my $homeserver=&domain($udom,'primary');
                   2243:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2244:             my $response;
                   2245:             if ($check eq 'id') {
                   2246:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2247:                                  $homeserver);
1.943     raeburn  2248:             } elsif ($check eq 'email') {
                   2249:                 $response=&reply('instemailrules:'.&escape($udom),
                   2250:                                  $homeserver);
1.923     raeburn  2251:             } else {
                   2252:                 $response=&reply('instuserrules:'.&escape($udom),
                   2253:                                  $homeserver);
                   2254:             }
1.912     raeburn  2255:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2256:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2257:                 ($response ne 'no_such_host')) {
                   2258:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2259:                 my @pairs=split(/\&/,$hashitems);
                   2260:                 foreach my $item (@pairs) {
                   2261:                     my ($key,$value)=split(/=/,$item,2);
                   2262:                     $key = &unescape($key);
                   2263:                     next if ($key =~ /^error: 2 /);
                   2264:                     $ruleshash{$key}=&thaw_unescape($value);
                   2265:                 }
                   2266:                 my @esc_order = split(/\&/,$orderitems);
                   2267:                 foreach my $item (@esc_order) {
                   2268:                     push(@ruleorder,&unescape($item));
                   2269:                 }
                   2270:             }
                   2271:         }
                   2272:     }
                   2273:     return (\%ruleshash,\@ruleorder);
                   2274: }
                   2275: 
1.976     raeburn  2276: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2277: 
                   2278: sub get_domain_defaults {
1.1172.2.35  raeburn  2279:     my ($domain,$ignore_cache) = @_;
                   2280:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2281:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2282:     unless ($ignore_cache) {
                   2283:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2284:         if (defined($cached)) {
                   2285:             if (ref($result) eq 'HASH') {
                   2286:                 return %{$result};
                   2287:             }
1.943     raeburn  2288:         }
                   2289:     }
                   2290:     my %domdefaults;
                   2291:     my %domconfig =
1.989     raeburn  2292:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2293:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2294:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2295:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2296:                                   'coursecategories','autoenroll',
                   2297:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2298:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2299:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2300:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2301:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2302:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2303:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2304:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2305:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2306:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2307:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2308:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2309:     } else {
                   2310:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2311:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2312:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2313:     }
1.976     raeburn  2314:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2315:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2316:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2317:         } else {
                   2318:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2319:         }
1.1172.2.6  raeburn  2320:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2321:         foreach my $item (@usertools) {
                   2322:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2323:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2324:             }
                   2325:         }
1.1172.2.29  raeburn  2326:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2327:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2328:         }
1.976     raeburn  2329:     }
1.985     raeburn  2330:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2331:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2332:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2333:         }
                   2334:     }
1.1172.2.9  raeburn  2335:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2336:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2337:     }
1.989     raeburn  2338:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2339:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2340:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2341:         }
                   2342:     }
1.1047    raeburn  2343:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2344:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2345:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2346:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2347:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2348:         }
1.1172.2.41  raeburn  2349:         foreach my $type (@coursetypes) {
                   2350:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2351:                 unless ($type eq 'community') {
                   2352:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2353:                 }
                   2354:             }
                   2355:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2356:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2357:             }
1.1172.2.60  raeburn  2358:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2359:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2360:                     $domdefaults{$type.'postsubtimeout'} =
                   2361:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2362:                 }
                   2363:             }
1.1172.2.30  raeburn  2364:         }
1.1172.2.67  raeburn  2365:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2366:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2367:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2368:                 if (@clonecodes) {
                   2369:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2370:                 }
                   2371:             }
                   2372:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2373:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2374:         }
1.1172.2.103  raeburn  2375:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2376:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2377:         }
1.1047    raeburn  2378:     }
1.1073    raeburn  2379:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2380:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2381:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2382:         }
                   2383:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2384:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2385:         }
1.1172.2.62  raeburn  2386:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2387:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2388:         }
1.1073    raeburn  2389:     }
1.1172.2.41  raeburn  2390:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2391:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2392:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2393:                             'approval','limit');
                   2394:             foreach my $type (@coursetypes) {
                   2395:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2396:                     my @mgrdc = ();
                   2397:                     foreach my $item (@settings) {
                   2398:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2399:                             push(@mgrdc,$item);
                   2400:                         }
                   2401:                     }
                   2402:                     if (@mgrdc) {
                   2403:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2404:                     }
                   2405:                 }
                   2406:             }
                   2407:         }
                   2408:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2409:             foreach my $type (@coursetypes) {
                   2410:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2411:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2412:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2413:                     }
                   2414:                 }
                   2415:             }
                   2416:         }
                   2417:     }
1.1172.2.46  raeburn  2418:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2419:         $domdefaults{'catauth'} = 'std';
                   2420:         $domdefaults{'catunauth'} = 'std';
                   2421:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2422:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2423:         }
                   2424:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2425:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2426:         }
                   2427:     }
1.1172.2.76  raeburn  2428:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2429:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2430:     }
1.1172.2.89  raeburn  2431:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2432:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2433:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2434:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2435:         }
                   2436:     }
1.1172.2.23  raeburn  2437:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2438:     return %domdefaults;
                   2439: }
                   2440: 
1.1172.2.106  raeburn  2441: sub get_dom_cats {
                   2442:     my ($dom) = @_;
                   2443:     return unless (&domain($dom));
                   2444:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2445:     unless (defined($cached)) {
                   2446:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2447:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2448:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2449:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2450:             } else {
                   2451:                 $cats = {};
                   2452:             }
                   2453:         } else {
                   2454:             $cats = {};
                   2455:         }
                   2456:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2457:     }
                   2458:     return $cats;
                   2459: }
                   2460: 
                   2461: sub get_dom_instcats {
                   2462:     my ($dom) = @_;
                   2463:     return unless (&domain($dom));
                   2464:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2465:     unless (defined($cached)) {
                   2466:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2467:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2468:         if ($totcodes > 0) {
                   2469:             my $caller = 'global';
                   2470:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2471:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2472:                 $instcats = {
                   2473:                                 codes => \%codes,
                   2474:                                 codetitles => \@codetitles,
                   2475:                                 cat_titles => \%cat_titles,
                   2476:                                 cat_order => \%cat_order,
                   2477:                             };
                   2478:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2479:             }
                   2480:         }
                   2481:     }
                   2482:     return $instcats;
                   2483: }
                   2484: 
                   2485: sub retrieve_instcodes {
                   2486:     my ($coursecodes,$dom) = @_;
                   2487:     my $totcodes;
                   2488:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2489:     foreach my $course (keys(%courses)) {
                   2490:         if (ref($courses{$course}) eq 'HASH') {
                   2491:             if ($courses{$course}{'inst_code'} ne '') {
                   2492:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2493:                 $totcodes ++;
                   2494:             }
                   2495:         }
                   2496:     }
                   2497:     return $totcodes;
                   2498: }
                   2499: 
1.1172.2.113  raeburn  2500: # --------------------------------------------- Get domain config for passwords
                   2501: 
                   2502: sub get_passwdconf {
                   2503:     my ($dom) = @_;
                   2504:     my (%passwdconf,$gotconf,$lookup);
                   2505:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2506:     if (defined($cached)) {
                   2507:         if (ref($result) eq 'HASH') {
                   2508:             %passwdconf = %{$result};
                   2509:             $gotconf = 1;
                   2510:         }
                   2511:     }
                   2512:     unless ($gotconf) {
                   2513:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2514:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2515:             %passwdconf = %{$domconfig{'passwords'}};
                   2516:         }
                   2517:         my $cachetime = 24*60*60;
                   2518:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2519:     }
                   2520:     return %passwdconf;
                   2521: }
                   2522: 
1.1172.2.118.  .1(raebu 2523:20): sub course_portal_url {
                   2524:20):     my ($cnum,$cdom) = @_;
                   2525:20):     my $chome = &homeserver($cnum,$cdom);
                   2526:20):     my $hostname = &hostname($chome);
                   2527:20):     my $protocol = $protocol{$chome};
                   2528:20):     $protocol = 'http' if ($protocol ne 'https');
                   2529:20):     my %domdefaults = &get_domain_defaults($cdom);
                   2530:20):     my $firsturl;
                   2531:20):     if ($domdefaults{'portal_def'}) {
                   2532:20):         $firsturl = $domdefaults{'portal_def'};
                   2533:20):     } else {
                   2534:20):         $firsturl = $protocol.'://'.$hostname;
                   2535:20):     }
                   2536:20):     return $firsturl;
                   2537:20): }
                   2538:20): 
1.344     www      2539: # --------------------------------------------------- Assign a key to a student
                   2540: 
                   2541: sub assign_access_key {
1.364     www      2542: #
                   2543: # a valid key looks like uname:udom#comments
                   2544: # comments are being appended
                   2545: #
1.498     www      2546:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2547:     $kdom=
1.620     albertel 2548:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2549:     $knum=
1.620     albertel 2550:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2551:     $cdom=
1.620     albertel 2552:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2553:     $cnum=
1.620     albertel 2554:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2555:     $udom=$env{'user.name'} unless (defined($udom));
                   2556:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2557:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2558:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2559:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2560:                                                   # assigned to this person
                   2561:                                                   # - this should not happen,
1.345     www      2562:                                                   # unless something went wrong
                   2563:                                                   # the first time around
                   2564: # ready to assign
1.364     www      2565:         $logentry=$1.'; '.$logentry;
1.496     www      2566:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2567:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2568: # key now belongs to user
1.346     www      2569: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2570:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2571:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2572:                 return 'ok';
                   2573:             } else {
                   2574:                 return 
                   2575:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2576: 	    }
                   2577:         } else {
                   2578:             return 'error: Could not assign key, try again later.';
                   2579:         }
1.364     www      2580:     } elsif (!$existing{$ckey}) {
1.345     www      2581: # the key does not exist
                   2582: 	return 'error: The key does not exist';
                   2583:     } else {
                   2584: # the key is somebody else's
                   2585: 	return 'error: The key is already in use';
                   2586:     }
1.344     www      2587: }
                   2588: 
1.364     www      2589: # ------------------------------------------ put an additional comment on a key
                   2590: 
                   2591: sub comment_access_key {
                   2592: #
                   2593: # a valid key looks like uname:udom#comments
                   2594: # comments are being appended
                   2595: #
                   2596:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2597:     $cdom=
1.620     albertel 2598:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2599:     $cnum=
1.620     albertel 2600:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2601:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2602:     if ($existing{$ckey}) {
                   2603:         $existing{$ckey}.='; '.$logentry;
                   2604: # ready to assign
1.367     www      2605:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2606:                                                  $cdom,$cnum) eq 'ok') {
                   2607: 	    return 'ok';
                   2608:         } else {
                   2609: 	    return 'error: Count not store comment.';
                   2610:         }
                   2611:     } else {
                   2612: # the key does not exist
                   2613: 	return 'error: The key does not exist';
                   2614:     }
                   2615: }
                   2616: 
1.344     www      2617: # ------------------------------------------------------ Generate a set of keys
                   2618: 
                   2619: sub generate_access_keys {
1.364     www      2620:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2621:     $cdom=
1.620     albertel 2622:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2623:     $cnum=
1.620     albertel 2624:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2625:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2626:     unless (($cdom) && ($cnum)) { return 0; }
                   2627:     if ($number>10000) { return 0; }
                   2628:     sleep(2); # make sure don't get same seed twice
                   2629:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2630:     my $total=0;
                   2631:     for (my $i=1;$i<=$number;$i++) {
                   2632:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2633:                   sprintf("%lx",int(100000*rand)).'-'.
                   2634:                   sprintf("%lx",int(100000*rand));
                   2635:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2636:        $newkey=~s/0/h/g; # and also 0 and O
                   2637:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2638:        if ($existing{$newkey}) {
                   2639:            $i--;
                   2640:        } else {
1.364     www      2641: 	  if (&put('accesskeys',
                   2642:               { $newkey => '# generated '.localtime().
1.620     albertel 2643:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2644:                            '; '.$logentry },
                   2645: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2646:               $total++;
                   2647: 	  }
                   2648:        }
                   2649:     }
1.620     albertel 2650:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2651:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2652:     return $total;
                   2653: }
                   2654: 
                   2655: # ------------------------------------------------------- Validate an accesskey
                   2656: 
                   2657: sub validate_access_key {
                   2658:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2659:     $cdom=
1.620     albertel 2660:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2661:     $cnum=
1.620     albertel 2662:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2663:     $udom=$env{'user.domain'} unless (defined($udom));
                   2664:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2665:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2666:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2667: }
                   2668: 
                   2669: # ------------------------------------- Find the section of student in a course
1.652     albertel 2670: sub devalidate_getsection_cache {
                   2671:     my ($udom,$unam,$courseid)=@_;
                   2672:     my $hashid="$udom:$unam:$courseid";
                   2673:     &devalidate_cache_new('getsection',$hashid);
                   2674: }
1.298     matthew  2675: 
1.815     albertel 2676: sub courseid_to_courseurl {
                   2677:     my ($courseid) = @_;
                   2678:     #already url style courseid
                   2679:     return $courseid if ($courseid =~ m{^/});
                   2680: 
                   2681:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2682: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2683: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2684: 	return "/$cdom/$cnum";
                   2685:     }
                   2686: 
                   2687:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2688:     if (exists($courseinfo{'num'})) {
                   2689: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2690:     }
                   2691: 
                   2692:     return undef;
                   2693: }
                   2694: 
1.298     matthew  2695: sub getsection {
                   2696:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2697:     my $cachetime=1800;
1.551     albertel 2698: 
                   2699:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2700:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2701:     if (defined($cached)) { return $result; }
                   2702: 
1.298     matthew  2703:     my %Pending; 
                   2704:     my %Expired;
                   2705:     #
                   2706:     # Each role can either have not started yet (pending), be active, 
                   2707:     #    or have expired.
                   2708:     #
                   2709:     # If there is an active role, we are done.
                   2710:     #
                   2711:     # If there is more than one role which has not started yet, 
                   2712:     #     choose the one which will start sooner
                   2713:     # If there is one role which has not started yet, return it.
                   2714:     #
                   2715:     # If there is more than one expired role, choose the one which ended last.
                   2716:     # If there is a role which has expired, return it.
                   2717:     #
1.815     albertel 2718:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2719:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2720:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2721:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2722:         my $section=$1;
                   2723:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2724:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2725:         my $now=time;
1.548     albertel 2726:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2727:             $Expired{$end}=$section;
                   2728:             next;
                   2729:         }
1.548     albertel 2730:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2731:             $Pending{$start}=$section;
                   2732:             next;
                   2733:         }
1.599     albertel 2734:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2735:     }
                   2736:     #
                   2737:     # Presumedly there will be few matching roles from the above
                   2738:     # loop and the sorting time will be negligible.
                   2739:     if (scalar(keys(%Pending))) {
                   2740:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2741:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2742:     } 
                   2743:     if (scalar(keys(%Expired))) {
                   2744:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2745:         my $time = pop(@sorted);
1.599     albertel 2746:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2747:     }
1.599     albertel 2748:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2749: }
1.70      www      2750: 
1.599     albertel 2751: sub save_cache {
                   2752:     &purge_remembered();
1.722     albertel 2753:     #&Apache::loncommon::validate_page();
1.620     albertel 2754:     undef(%env);
1.780     albertel 2755:     undef($env_loaded);
1.599     albertel 2756: }
1.452     albertel 2757: 
1.599     albertel 2758: my $to_remember=-1;
                   2759: my %remembered;
                   2760: my %accessed;
                   2761: my $kicks=0;
                   2762: my $hits=0;
1.849     albertel 2763: sub make_key {
                   2764:     my ($name,$id) = @_;
1.872     albertel 2765:     if (length($id) > 65 
                   2766: 	&& length(&escape($id)) > 200) {
                   2767: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2768:     }
1.849     albertel 2769:     return &escape($name.':'.$id);
                   2770: }
                   2771: 
1.599     albertel 2772: sub devalidate_cache_new {
                   2773:     my ($name,$id,$debug) = @_;
                   2774:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2775:     my $remembered_id=$name.':'.$id;
1.849     albertel 2776:     $id=&make_key($name,$id);
1.599     albertel 2777:     $memcache->delete($id);
1.1172.2.81  raeburn  2778:     delete($remembered{$remembered_id});
                   2779:     delete($accessed{$remembered_id});
1.599     albertel 2780: }
                   2781: 
                   2782: sub is_cached_new {
                   2783:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2784:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2785:                                      # keys in %remembered hash, which persists for
                   2786:                                      # duration of request (no restriction on key length).
                   2787:     if (exists($remembered{$remembered_id})) {
                   2788: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2789: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2790: 	$hits++;
1.1172.2.81  raeburn  2791: 	return ($remembered{$remembered_id},1);
1.599     albertel 2792:     }
1.1172.2.81  raeburn  2793:     $id=&make_key($name,$id);
1.599     albertel 2794:     my $value = $memcache->get($id);
                   2795:     if (!(defined($value))) {
                   2796: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2797: 	return (undef,undef);
1.416     albertel 2798:     }
1.599     albertel 2799:     if ($value eq '__undef__') {
                   2800: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2801: 	$value=undef;
                   2802:     }
1.1172.2.81  raeburn  2803:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2804:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2805:     return ($value,1);
                   2806: }
                   2807: 
                   2808: sub do_cache_new {
                   2809:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2810:     my $remembered_id=$name.':'.$id;
1.849     albertel 2811:     $id=&make_key($name,$id);
1.599     albertel 2812:     my $setvalue=$value;
                   2813:     if (!defined($setvalue)) {
                   2814: 	$setvalue='__undef__';
                   2815:     }
1.623     albertel 2816:     if (!defined($time) ) {
                   2817: 	$time=600;
                   2818:     }
1.599     albertel 2819:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2820:     my $result = $memcache->set($id,$setvalue,$time);
                   2821:     if (! $result) {
1.872     albertel 2822: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2823: 	$memcache->disconnect_all();
1.872     albertel 2824:     }
1.600     albertel 2825:     # need to make a copy of $value
1.1172.2.81  raeburn  2826:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2827:     return $value;
                   2828: }
                   2829: 
                   2830: sub make_room {
1.1172.2.81  raeburn  2831:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2832: 
1.1172.2.81  raeburn  2833:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2834:                                     : $value;
1.599     albertel 2835:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2836:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2837:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2838:     my $to_kick;
                   2839:     my $max_time=0;
                   2840:     foreach my $other (keys(%accessed)) {
                   2841: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2842: 	    $to_kick=$other;
                   2843: 	    $max_time=&tv_interval($accessed{$other});
                   2844: 	}
                   2845:     }
                   2846:     delete($remembered{$to_kick});
                   2847:     delete($accessed{$to_kick});
                   2848:     $kicks++;
                   2849:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2850:     return;
                   2851: }
                   2852: 
1.599     albertel 2853: sub purge_remembered {
1.604     albertel 2854:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2855:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2856:     undef(%remembered);
                   2857:     undef(%accessed);
1.428     albertel 2858: }
1.70      www      2859: # ------------------------------------- Read an entry from a user's environment
                   2860: 
                   2861: sub userenvironment {
                   2862:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2863:     my $items;
                   2864:     foreach my $item (@what) {
                   2865:         $items.=&escape($item).'&';
                   2866:     }
                   2867:     $items=~s/\&$//;
1.70      www      2868:     my %returnhash=();
1.1009    raeburn  2869:     my $uhome = &homeserver($unam,$udom);
                   2870:     unless ($uhome eq 'no_host') {
                   2871:         my @answer=split(/\&/, 
                   2872:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2873:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2874:             return %returnhash;
                   2875:         }
1.1009    raeburn  2876:         my $i;
                   2877:         for ($i=0;$i<=$#what;$i++) {
                   2878: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2879:         }
1.70      www      2880:     }
                   2881:     return %returnhash;
1.1       albertel 2882: }
                   2883: 
1.617     albertel 2884: # ---------------------------------------------------------- Get a studentphoto
                   2885: sub studentphoto {
                   2886:     my ($udom,$unam,$ext) = @_;
                   2887:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2888:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2889:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2890:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2891:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2892:             } else {
                   2893:                 my ($result,$perm_reqd)=
1.707     albertel 2894: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2895:                 if ($result eq 'ok') {
                   2896:                     if (!($perm_reqd eq 'yes')) {
                   2897:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2898:                     }
                   2899:                 }
                   2900:             }
                   2901:         }
                   2902:     } else {
                   2903:         my ($result,$perm_reqd) = 
1.707     albertel 2904: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2905:         if ($result eq 'ok') {
                   2906:             if (!($perm_reqd eq 'yes')) {
                   2907:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2908:             }
                   2909:         }
                   2910:     }
                   2911:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2912: }
                   2913: 
                   2914: sub retrievestudentphoto {
                   2915:     my ($udom,$unam,$ext,$type) = @_;
                   2916:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2917:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2918:     if ($ret eq 'ok') {
                   2919:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2920:         if ($type eq 'thumbnail') {
                   2921:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2922:         }
                   2923:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2924:         return $tokenurl;
                   2925:     } else {
                   2926:         if ($type eq 'thumbnail') {
                   2927:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2928:         } else { 
                   2929:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2930:         }
1.617     albertel 2931:     }
                   2932: }
                   2933: 
1.263     www      2934: # -------------------------------------------------------------------- New chat
                   2935: 
                   2936: sub chatsend {
1.724     raeburn  2937:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2938:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2939:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2940:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2941:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2942: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2943: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2944: }
                   2945: 
                   2946: # ------------------------------------------ Find current version of a resource
                   2947: 
                   2948: sub getversion {
                   2949:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2950:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2951:     return &currentversion(&filelocation('',$fname));
                   2952: }
                   2953: 
                   2954: sub currentversion {
                   2955:     my $fname=shift;
                   2956:     my $author=$fname;
                   2957:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2958:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2959:     my $home=&homeserver($uname,$udom);
1.292     www      2960:     if ($home eq 'no_host') { 
                   2961:         return -1; 
                   2962:     }
1.1112    www      2963:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2964:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2965: 	return -1;
                   2966:     }
1.1112    www      2967:     return $answer;
1.263     www      2968: }
                   2969: 
1.1111    www      2970: #
                   2971: # Return special version number of resource if set by override, empty otherwise
                   2972: #
                   2973: sub usedversion {
                   2974:     my $fname=shift;
                   2975:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2976:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2977:     if ($urlversion) { return $urlversion; }
                   2978:     return '';
                   2979: }
                   2980: 
1.1       albertel 2981: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2982: 
1.1       albertel 2983: sub subscribe {
                   2984:     my $fname=shift;
1.761     raeburn  2985:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2986:     $fname=~s/[\n\r]//g;
1.1       albertel 2987:     my $author=$fname;
                   2988:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2989:     my ($udom,$uname)=split(/\//,$author);
                   2990:     my $home=homeserver($uname,$udom);
1.335     albertel 2991:     if ($home eq 'no_host') {
                   2992:         return 'not_found';
1.1       albertel 2993:     }
                   2994:     my $answer=reply("sub:$fname",$home);
1.64      www      2995:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2996: 	$answer.=' by '.$home;
                   2997:     }
1.1       albertel 2998:     return $answer;
                   2999: }
                   3000:     
1.8       www      3001: # -------------------------------------------------------------- Replicate file
                   3002: 
                   3003: sub repcopy {
                   3004:     my $filename=shift;
1.23      www      3005:     $filename=~s/\/+/\//g;
1.1142    raeburn  3006:     my $londocroot = $perlvar{'lonDocRoot'};
                   3007:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3008:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3009:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3010: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3011: 	return &repcopy_userfile($filename);
                   3012:     }
1.532     albertel 3013:     $filename=~s/[\n\r]//g;
1.8       www      3014:     my $transname="$filename.in.transfer";
1.828     www      3015: # FIXME: this should flock
1.607     raeburn  3016:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3017:     my $remoteurl=subscribe($filename);
1.64      www      3018:     if ($remoteurl =~ /^con_lost by/) {
                   3019: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3020:            return 'unavailable';
1.8       www      3021:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3022: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3023: 	   return 'not_found';
1.64      www      3024:     } elsif ($remoteurl =~ /^rejected by/) {
                   3025: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3026:            return 'forbidden';
1.20      www      3027:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3028:            return 'ok';
1.8       www      3029:     } else {
1.290     www      3030:         my $author=$filename;
                   3031:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3032:         my ($udom,$uname)=split(/\//,$author);
                   3033:         my $home=homeserver($uname,$udom);
                   3034:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3035:            my @parts=split(/\//,$filename);
                   3036:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3037:            if ($path ne "$londocroot/res") {
1.8       www      3038:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3039: 	       return 'bad_request';
1.8       www      3040:            }
                   3041:            my $count;
                   3042:            for ($count=5;$count<$#parts;$count++) {
                   3043:                $path.="/$parts[$count]";
                   3044:                if ((-e $path)!=1) {
                   3045: 		   mkdir($path,0777);
                   3046:                }
                   3047:            }
                   3048:            my $ua=new LWP::UserAgent;
                   3049:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3050:            my $response=$ua->request($request,$transname);
                   3051:            if ($response->is_error()) {
                   3052: 	       unlink($transname);
                   3053:                my $message=$response->status_line;
1.672     albertel 3054:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3055:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3056:                return 'unavailable';
1.8       www      3057:            } else {
1.16      www      3058: 	       if ($remoteurl!~/\.meta$/) {
                   3059:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3060:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3061:                   if ($mresponse->is_error()) {
                   3062: 		      unlink($filename.'.meta');
                   3063:                       &logthis(
1.672     albertel 3064:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3065:                   }
                   3066: 	       }
1.8       www      3067:                rename($transname,$filename);
1.607     raeburn  3068:                return 'ok';
1.8       www      3069:            }
1.290     www      3070:        }
1.8       www      3071:     }
1.330     www      3072: }
                   3073: 
                   3074: # ------------------------------------------------ Get server side include body
                   3075: sub ssi_body {
1.381     albertel 3076:     my ($filelink,%form)=@_;
1.606     matthew  3077:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3078:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3079:     }
1.953     www      3080:     my $output='';
                   3081:     my $response;
1.980     raeburn  3082:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3083:        ($output,$response)=&externalssi($filelink);
1.953     www      3084:     } else {
1.1004    droeschl 3085:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3086:        $filelink .= 'inhibitmenu=yes';
1.953     www      3087:        ($output,$response)=&ssi($filelink,%form);
                   3088:     }
1.778     albertel 3089:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3090:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3091:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3092:     if (wantarray) {
                   3093:         return ($output, $response);
                   3094:     } else {
                   3095:         return $output;
                   3096:     }
1.8       www      3097: }
                   3098: 
1.15      www      3099: # --------------------------------------------------------- Server Side Include
                   3100: 
1.782     albertel 3101: sub absolute_url {
                   3102:     my ($host_name) = @_;
                   3103:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3104:     if ($host_name eq '') {
                   3105: 	$host_name = $ENV{'SERVER_NAME'};
                   3106:     }
                   3107:     return $protocol.$host_name;
                   3108: }
                   3109: 
1.942     foxr     3110: #
                   3111: #   Server side include.
                   3112: # Parameters:
                   3113: #  fn     Possibly encrypted resource name/id.
                   3114: #  form   Hash that describes how the rendering should be done
                   3115: #         and other things.
1.944     foxr     3116: # Returns:
1.950     raeburn  3117: #   Scalar context: The content of the response.
                   3118: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3119: #     
1.15      www      3120: sub ssi {
                   3121: 
1.944     foxr     3122:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3123:     my ($request,$response);
1.711     albertel 3124: 
                   3125:     $form{'no_update_last_known'}=1;
1.895     albertel 3126:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3127:     if (%form) {
1.782     albertel 3128:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3129:       $request->content(join('&',map {
                   3130:             my $name = escape($_);
                   3131:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3132:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3133:             : &escape($form{$_}) );
                   3134:         } keys(%form)));
1.23      www      3135:     } else {
1.782     albertel 3136:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3137:     }
                   3138: 
1.15      www      3139:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3140: 
1.1172.2.101  raeburn  3141:     if (($env{'request.course.id'}) &&
                   3142:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3143:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3144:         ($form{'grade_symb'} ne '') &&
                   3145:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3146:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3147:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3148:             my $ua=new LWP::UserAgent;
                   3149:             $ua->local_address('127.0.0.1');
                   3150:             $response = $ua->request($request);
                   3151:         } else {
                   3152:             {
                   3153:                 require LWP::Protocol::http;
                   3154:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3155:                 my $ua=new LWP::UserAgent;
                   3156:                 $response = $ua->request($request);
                   3157:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3158:             }
                   3159:         }
                   3160:     } else {
                   3161:         my $ua=new LWP::UserAgent;
                   3162:         $response = $ua->request($request);
                   3163:     }
1.944     foxr     3164:     if (wantarray) {
1.1172.2.3  raeburn  3165: 	return ($response->content, $response);
1.944     foxr     3166:     } else {
1.1172.2.3  raeburn  3167: 	return $response->content;
1.942     foxr     3168:     }
1.324     www      3169: }
                   3170: 
                   3171: sub externalssi {
                   3172:     my ($url)=@_;
                   3173:     my $ua=new LWP::UserAgent;
                   3174:     my $request=new HTTP::Request('GET',$url);
                   3175:     my $response=$ua->request($request);
1.954     raeburn  3176:     if (wantarray) {
                   3177:         return ($response->content, $response);
                   3178:     } else {
                   3179:         return $response->content;
                   3180:     }
1.15      www      3181: }
1.254     www      3182: 
1.1172.2.98  raeburn  3183: # If the local copy of a replicated resource is outdated, trigger a
                   3184: # connection from the homeserver to flush the delayed queue. If no update
                   3185: # happens, remove local copies of outdated resource (and corresponding
                   3186: # metadata file).
                   3187: 
                   3188: sub remove_stale_resfile {
                   3189:     my ($url) = @_;
                   3190:     my $removed;
                   3191:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3192:         my $audom = $1;
                   3193:         my $auname = $2;
                   3194:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3195:             my $homeserver = &homeserver($auname,$audom);
                   3196:             unless (($homeserver eq 'no_host') ||
                   3197:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3198:                 my $fname = &filelocation('',$url);
                   3199:                 if (-e $fname) {
                   3200:                     my $ua=new LWP::UserAgent;
                   3201:                     $ua->timeout(5);
                   3202:                     my $protocol = $protocol{$homeserver};
                   3203:                     $protocol = 'http' if ($protocol ne 'https');
                   3204:                     my $hostname = &hostname($homeserver);
                   3205:                     if ($hostname) {
                   3206:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   3207:                         my $request=new HTTP::Request('HEAD',$uri);
                   3208:                         my $response=$ua->request($request);
                   3209:                         if ($response->is_success()) {
                   3210:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3211:                             my $locmodtime = (stat($fname))[9];
                   3212:                             if ($locmodtime < $remmodtime) {
                   3213:                                 my $stale;
                   3214:                                 my $answer = &reply('pong',$homeserver);
                   3215:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3216:                                     sleep(0.2);
                   3217:                                     $locmodtime = (stat($fname))[9];
                   3218:                                     if ($locmodtime < $remmodtime) {
                   3219:                                         my $posstransfer = $fname.'.in.transfer';
                   3220:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3221:                                             $removed = 1;
                   3222:                                         } else {
                   3223:                                             $stale = 1;
                   3224:                                         }
                   3225:                                     } else {
                   3226:                                         $removed = 1;
                   3227:                                     }
                   3228:                                 } else {
                   3229:                                     $stale = 1;
                   3230:                                 }
                   3231:                                 if ($stale) {
                   3232:                                     unlink($fname);
                   3233:                                     if ($uri!~/\.meta$/) {
                   3234:                                         unlink($fname.'.meta');
                   3235:                                     }
                   3236:                                     &reply("unsub:$fname",$homeserver);
                   3237:                                     $removed = 1;
                   3238:                                 }
                   3239:                             }
                   3240:                         }
                   3241:                     }
                   3242:                 }
                   3243:             }
                   3244:         }
                   3245:     }
                   3246:     return $removed;
                   3247: }
                   3248: 
1.492     albertel 3249: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3250: 
                   3251: sub allowuploaded {
                   3252:     my ($srcurl,$url)=@_;
                   3253:     $url=&clutter(&declutter($url));
                   3254:     my $dir=$url;
                   3255:     $dir=~s/\/[^\/]+$//;
                   3256:     my %httpref=();
                   3257:     my $httpurl=&hreflocation('',$url);
                   3258:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3259:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3260: }
1.477     raeburn  3261: 
1.1172.2.13  raeburn  3262: #
                   3263: # Determine if the current user should be able to edit a particular resource,
                   3264: # when viewing in course context.
                   3265: # (a) When viewing resource used to determine if "Edit" item is included in
                   3266: #     Functions.
                   3267: # (b) When displaying folder contents in course editor, used to determine if
                   3268: #     "Edit" link will be displayed alongside resource.
                   3269: #
                   3270: #  input: six args -- filename (decluttered), course number, course domain,
                   3271: #                   url, symb (if registered) and group (if this is a group
                   3272: #                   item -- e.g., bulletin board, group page etc.).
                   3273: #  output: array of five scalars --
                   3274: #          $cfile -- url for file editing if editable on current server
                   3275: #          $home -- homeserver of resource (i.e., for author if published,
                   3276: #                                           or course if uploaded.).
                   3277: #          $switchserver --  1 if server switch will be needed.
                   3278: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3279: #          $forceview -- 1 if icon/link should be to go to view mode
                   3280: #
                   3281: 
                   3282: sub can_edit_resource {
                   3283:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3284:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3285: #
                   3286: # For aboutme pages user can only edit his/her own.
                   3287: #
                   3288:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3289:         my ($sdom,$sname) = ($1,$2);
                   3290:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3291:             $home = $env{'user.home'};
                   3292:             $cfile = $resurl;
                   3293:             if ($env{'form.forceedit'}) {
                   3294:                 $forceview = 1;
                   3295:             } else {
                   3296:                 $forceedit = 1;
                   3297:             }
                   3298:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3299:         } else {
                   3300:             return;
                   3301:         }
                   3302:     }
                   3303: 
                   3304:     if ($env{'request.course.id'}) {
                   3305:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3306:         if ($group ne '') {
                   3307: # if this is a group homepage or group bulletin board, check group privs
                   3308:             my $allowed = 0;
                   3309:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3310:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3311:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3312:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3313:                     $allowed = 1;
                   3314:                 }
                   3315:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3316:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3317:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3318:                     $allowed = 1;
                   3319:                 }
                   3320:             }
                   3321:             if ($allowed) {
                   3322:                 $home=&homeserver($cnum,$cdom);
                   3323:                 if ($env{'form.forceedit'}) {
                   3324:                     $forceview = 1;
                   3325:                 } else {
                   3326:                     $forceedit = 1;
                   3327:                 }
                   3328:                 $cfile = $resurl;
                   3329:             } else {
                   3330:                 return;
                   3331:             }
                   3332:         } else {
1.1172.2.15  raeburn  3333:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3334:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3335:                     return;
                   3336:                 }
                   3337:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3338: #
                   3339: # No edit allowed where CC has switched to student role.
                   3340: #
                   3341:                 return;
                   3342:             }
                   3343:         }
                   3344:     }
                   3345: 
                   3346:     if ($file ne '') {
                   3347:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3348:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3349:                 $uploaded = 1;
                   3350:                 $incourse = 1;
                   3351:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3352:                     $cfile = &hreflocation('',$file);
                   3353:                     if ($env{'form.forceedit'}) {
                   3354:                         $forceview = 1;
                   3355:                     } else {
                   3356:                         $forceedit = 1;
                   3357:                     }
                   3358:                 }
                   3359:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3360:                 $incourse = 1;
                   3361:                 if ($env{'form.forceedit'}) {
                   3362:                     $forceview = 1;
                   3363:                 } else {
                   3364:                     $forceedit = 1;
                   3365:                 }
                   3366:                 $cfile = $resurl;
                   3367:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3368:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3369:                     $incourse = 1;
                   3370:                     if ($env{'form.forceedit'}) {
                   3371:                         $forceview = 1;
                   3372:                     } else {
                   3373:                         $forceedit = 1;
                   3374:                     }
                   3375:                     $cfile = $resurl;
                   3376:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3377:                     $incourse = 1;
                   3378:                     $cfile = $resurl.'/smpedit';
                   3379:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3380:                     $incourse = 1;
                   3381:                     if ($env{'form.forceedit'}) {
                   3382:                         $forceview = 1;
                   3383:                     } else {
                   3384:                         $forceedit = 1;
                   3385:                     }
                   3386:                     $cfile = $resurl;
1.1172.2.118.  .1(raebu 3387:20):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3388:20):                     $incourse = 1;
                   3389:20):                     if ($env{'form.forceedit'}) {
                   3390:20):                         $forceview = 1;
                   3391:20):                     } else {
                   3392:20):                         $forceedit = 1;
                   3393:20):                     }
                   3394:20):                     $cfile = $resurl;
1.1172.2.15  raeburn  3395:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3396:                     $incourse = 1;
                   3397:                     if ($env{'form.forceedit'}) {
                   3398:                         $forceview = 1;
                   3399:                     } else {
                   3400:                         $forceedit = 1;
                   3401:                     }
                   3402:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3403:                 }
                   3404:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3405:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3406:                 if (&is_on_map($template)) {
                   3407:                     $incourse = 1;
                   3408:                     $forceview = 1;
                   3409:                     $cfile = $template;
                   3410:                 }
                   3411:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3412:                 $incourse = 1;
                   3413:                 if ($env{'form.forceedit'}) {
                   3414:                     $forceview = 1;
                   3415:                 } else {
                   3416:                     $forceedit = 1;
                   3417:                 }
                   3418:                 $cfile = $resurl;
1.1172.2.118.  .1(raebu 3419:20):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3420:20):                 $incourse = 1;
                   3421:20):                 if ($env{'form.forceedit'}) {
                   3422:20):                     $forceview = 1;
                   3423:20):                 } else {
                   3424:20):                     $forceedit = 1;
                   3425:20):                 }
                   3426:20):                 $cfile = $resurl;
1.1172.2.13  raeburn  3427:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3428:                 $incourse = 1;
                   3429:                 $forceview = 1;
                   3430:                 if ($symb) {
                   3431:                     my ($map,$id,$res)=&decode_symb($symb);
                   3432:                     $env{'request.symb'} = $symb;
                   3433:                     $cfile = &clutter($res);
                   3434:                 } else {
                   3435:                     $cfile = $env{'form.suppurl'};
1.1172.2.118.  .1(raebu 3436:20):                     my $escfile = &unescape($cfile);
                   3437:20):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3438:20):                         $cfile = '/adm/wrapper'.$escfile;
                   3439:20):                     } else {
                   3440:20):                         $escfile =~ s{^http://}{};
                   3441:20):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3442:20):                     }
1.1172.2.13  raeburn  3443:                 }
1.1172.2.31  raeburn  3444:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3445:                 if ($env{'form.forceedit'}) {
                   3446:                     $forceview = 1;
                   3447:                 } else {
                   3448:                     $forceedit = 1;
                   3449:                 }
                   3450:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3451:             }
                   3452:         }
                   3453:         if ($uploaded || $incourse) {
                   3454:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3455:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3456:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3457:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3458:             # Check that the user has permission to edit this resource
                   3459:             my $setpriv = 1;
                   3460:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3461:             if (defined($cfudom)) {
                   3462:                 $home=&homeserver($cfuname,$cfudom);
                   3463:                 $cfile=$file;
                   3464:             }
                   3465:         }
                   3466:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3467:             (($home ne '') && ($home ne 'no_host'))) {
                   3468:             my @ids=&current_machine_ids();
                   3469:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3470:                 $switchserver=1;
                   3471:             }
                   3472:         }
                   3473:     }
                   3474:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3475: }
                   3476: 
                   3477: sub is_course_upload {
                   3478:     my ($file,$cnum,$cdom) = @_;
                   3479:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3480:     $uploadpath =~ s{^\/}{};
                   3481:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3482:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3483:         return 1;
                   3484:     }
                   3485:     return;
                   3486: }
                   3487: 
                   3488: sub in_course {
                   3489:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3490:     if ($hideprivileged) {
                   3491:         my $skipuser;
1.1172.2.23  raeburn  3492:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3493:         my @possdoms = ($cdom);
                   3494:         if ($coursehash{'checkforpriv'}) {
                   3495:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3496:         }
                   3497:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3498:             $skipuser = 1;
                   3499:             if ($coursehash{'nothideprivileged'}) {
                   3500:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3501:                     my $user;
                   3502:                     if ($item =~ /:/) {
                   3503:                         $user = $item;
                   3504:                     } else {
                   3505:                         $user = join(':',split(/[\@]/,$item));
                   3506:                     }
                   3507:                     if ($user eq $uname.':'.$udom) {
                   3508:                         undef($skipuser);
                   3509:                         last;
                   3510:                     }
                   3511:                 }
                   3512:             }
                   3513:             if ($skipuser) {
                   3514:                 return 0;
                   3515:             }
                   3516:         }
                   3517:     }
                   3518:     $type ||= 'any';
                   3519:     if (!defined($cdom) || !defined($cnum)) {
                   3520:         my $cid  = $env{'request.course.id'};
                   3521:         $cdom = $env{'course.'.$cid.'.domain'};
                   3522:         $cnum = $env{'course.'.$cid.'.num'};
                   3523:     }
                   3524:     my $typesref;
                   3525:     if (($type eq 'any') || ($type eq 'all')) {
                   3526:         $typesref = ['active','previous','future'];
                   3527:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3528:         $typesref = [$type];
                   3529:     }
                   3530:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3531:                               $typesref,undef,[$cdom]);
                   3532:     my ($tmp) = keys(%roles);
                   3533:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3534:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3535:     if (@course_roles > 0) {
                   3536:         return 1;
                   3537:     }
                   3538:     return 0;
                   3539: }
                   3540: 
1.478     albertel 3541: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3542: # input: action, courseID, current domain, intended
1.637     raeburn  3543: #        path to file, source of file, instruction to parse file for objects,
                   3544: #        ref to hash for embedded objects,
                   3545: #        ref to hash for codebase of java objects.
1.1095    raeburn  3546: #        reference to scalar to accommodate mime type determined
                   3547: #          from File::MMagic if $parser = parse.
1.637     raeburn  3548: #
1.485     raeburn  3549: # output: url to file (if action was uploaddoc), 
                   3550: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3551: #
1.478     albertel 3552: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3553: # course.
1.477     raeburn  3554: #
1.478     albertel 3555: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3556: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3557: #          course's home server.
1.477     raeburn  3558: #
1.478     albertel 3559: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3560: #          be copied from $source (current location) to 
                   3561: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3562: #         and will then be copied to
                   3563: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3564: #         course's home server.
1.485     raeburn  3565: #
1.481     raeburn  3566: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3567: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3568: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3569: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3570: #         in course's home server.
1.637     raeburn  3571: #
1.477     raeburn  3572: 
                   3573: sub process_coursefile {
1.1095    raeburn  3574:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3575:         $mimetype)=@_;
1.477     raeburn  3576:     my $fetchresult;
1.638     albertel 3577:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3578:     if ($action eq 'propagate') {
1.638     albertel 3579:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3580: 			     $home);
1.481     raeburn  3581:     } else {
1.477     raeburn  3582:         my $fpath = '';
                   3583:         my $fname = $file;
1.478     albertel 3584:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3585:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3586:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3587:         if ($action eq 'copy') {
                   3588:             if ($source eq '') {
                   3589:                 $fetchresult = 'no source file';
                   3590:                 return $fetchresult;
                   3591:             } else {
                   3592:                 my $destination = $filepath.'/'.$fname;
                   3593:                 rename($source,$destination);
                   3594:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3595:                                  $home);
1.481     raeburn  3596:             }
                   3597:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3598:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3599:             print $fh $env{'form.'.$source};
1.481     raeburn  3600:             close($fh);
1.637     raeburn  3601:             if ($parser eq 'parse') {
1.1024    raeburn  3602:                 my $mm = new File::MMagic;
1.1095    raeburn  3603:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3604:                 if ($type eq 'text/html') {
1.1024    raeburn  3605:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3606:                     unless ($parse_result eq 'ok') {
                   3607:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3608:                     }
1.637     raeburn  3609:                 }
1.1095    raeburn  3610:                 if (ref($mimetype)) {
                   3611:                     $$mimetype = $type;
                   3612:                 } 
1.637     raeburn  3613:             }
1.477     raeburn  3614:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3615:                                  $home);
1.481     raeburn  3616:             if ($fetchresult eq 'ok') {
                   3617:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3618:             } else {
                   3619:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3620:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3621:                 return '/adm/notfound.html';
                   3622:             }
1.477     raeburn  3623:         }
                   3624:     }
1.485     raeburn  3625:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3626:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3627:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3628:     }
                   3629:     return $fetchresult;
                   3630: }
                   3631: 
1.637     raeburn  3632: sub build_filepath {
                   3633:     my ($fpath) = @_;
                   3634:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3635:     unless ($fpath eq '') {
                   3636:         my @parts=split('/',$fpath);
                   3637:         foreach my $part (@parts) {
                   3638:             $filepath.= '/'.$part;
                   3639:             if ((-e $filepath)!=1) {
                   3640:                 mkdir($filepath,0777);
                   3641:             }
                   3642:         }
                   3643:     }
                   3644:     return $filepath;
                   3645: }
                   3646: 
                   3647: sub store_edited_file {
1.638     albertel 3648:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3649:     my $file = $primary_url;
                   3650:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3651:     my $fpath = '';
                   3652:     my $fname = $file;
                   3653:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3654:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3655:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3656:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3657:     print $fh $content;
                   3658:     close($fh);
1.638     albertel 3659:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3660:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3661: 			  $home);
1.637     raeburn  3662:     if ($$fetchresult eq 'ok') {
                   3663:         return '/uploaded/'.$fpath.'/'.$fname;
                   3664:     } else {
1.638     albertel 3665:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3666: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3667:         return '/adm/notfound.html';
                   3668:     }
                   3669: }
                   3670: 
1.531     albertel 3671: sub clean_filename {
1.831     albertel 3672:     my ($fname,$args)=@_;
1.315     www      3673: # Replace Windows backslashes by forward slashes
1.257     www      3674:     $fname=~s/\\/\//g;
1.831     albertel 3675:     if (!$args->{'keep_path'}) {
                   3676:         # Get rid of everything but the actual filename
                   3677: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3678:     }
1.315     www      3679: # Replace spaces by underscores
                   3680:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3681: # Transliterate non-ascii text to ascii
                   3682:     my $lang = &Apache::lonlocal::current_language();
                   3683:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3684: # Replace all other weird characters by nothing
1.831     albertel 3685:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3686: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3687: # numbers
                   3688:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3689:     return $fname;
                   3690: }
1.1172.2.110  raeburn  3691: 
1.1051    raeburn  3692: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3693: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3694: # image with the same aspect ratio as the original, but with dimensions which do 
                   3695: # not exceed $resizewidth and $resizeheight.
                   3696:  
1.984     neumanie 3697: sub resizeImage {
1.1051    raeburn  3698:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3699:     my $ima = Image::Magick->new;
                   3700:     my $resized;
                   3701:     if (-e $img_path) {
                   3702:         $ima->Read($img_path);
                   3703:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3704:             my $width = $ima->Get('width');
                   3705:             my $height = $ima->Get('height');
                   3706:             if ($width > $resizewidth) {
                   3707: 	        my $factor = $width/$resizewidth;
                   3708:                 my $newheight = $height/$factor;
                   3709:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3710:                 $resized = 1;
                   3711:             }
                   3712:         }
                   3713:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3714:             my $width = $ima->Get('width');
                   3715:             my $height = $ima->Get('height');
                   3716:             if ($height > $resizeheight) {
                   3717:                 my $factor = $height/$resizeheight;
                   3718:                 my $newwidth = $width/$factor;
                   3719:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3720:                 $resized = 1;
                   3721:             }
                   3722:         }
                   3723:         if ($resized) {
                   3724:             $ima->Write($img_path);
                   3725:         }
                   3726:     }
                   3727:     return;
1.977     amueller 3728: }
                   3729: 
1.608     albertel 3730: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3731: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3732: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3733: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3734: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3735: #                   if 'coursedoc': upload to the current course
                   3736: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3737: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3738: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3739: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3740: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3741: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3742: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3743: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3744: #        $allfiles - reference to hash for embedded objects
                   3745: #        $codebase - reference to hash for codebase of java objects
                   3746: #        $desuname - username for permanent storage of uploaded file
                   3747: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3748: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3749: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3750: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3751: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3752: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3753: #                    from File::MMagic.
1.858     raeburn  3754: # 
1.686     albertel 3755: # output: url of file in userspace, or error: <message> 
                   3756: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3757: 
1.531     albertel 3758: sub userfileupload {
1.1090    raeburn  3759:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3760:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3761:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3762:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3763:     $fname=&clean_filename($fname);
1.1090    raeburn  3764:     # See if there is anything left
1.257     www      3765:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3766:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3767:     if ($fname =~ /^\./) {
                   3768:         my ($s,$usec) = &gettimeofday();
                   3769:         while (length($usec) < 6) {
                   3770:             $usec = '0'.$usec;
                   3771:         }
                   3772:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3773:     }
1.1090    raeburn  3774:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3775:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3776:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3777:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3778:         my $now = time;
1.1090    raeburn  3779:         my $filepath;
1.1095    raeburn  3780:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3781:              $filepath = 'tmp/helprequests/'.$now;
                   3782:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3783:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3784:                          '_'.$env{'user.domain'}.'/pending';
                   3785:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3786:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3787:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3788:                 $docudom = $destudom;
                   3789:             } else {
                   3790:                 $docudom = $env{'user.domain'};
                   3791:             }
1.1172.2.96  raeburn  3792:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3793:                 $docuname = $destuname;
                   3794:             } else {
                   3795:                 $docuname = $env{'user.name'};
                   3796:             }
                   3797:             if (exists($env{'form.group'})) {
                   3798:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3799:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3800:             }
                   3801:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3802:             if ($context eq 'canceloverwrite') {
                   3803:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3804:                 if (-e  $tempfile) {
                   3805:                     my @info = stat($tempfile);
                   3806:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3807:                         unlink($tempfile);
                   3808:                     }
                   3809:                 }
                   3810:                 return;
1.523     raeburn  3811:             }
                   3812:         }
1.1090    raeburn  3813:         # Create the directory if not present
1.741     raeburn  3814:         my @parts=split(/\//,$filepath);
                   3815:         my $fullpath = $perlvar{'lonDaemons'};
                   3816:         for (my $i=0;$i<@parts;$i++) {
                   3817:             $fullpath .= '/'.$parts[$i];
                   3818:             if ((-e $fullpath)!=1) {
                   3819:                 mkdir($fullpath,0777);
                   3820:             }
                   3821:         }
1.1172.2.96  raeburn  3822:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3823:         print $fh $env{'form.'.$formname};
                   3824:         close($fh);
1.1090    raeburn  3825:         if ($context eq 'existingfile') {
                   3826:             my @info = stat($fullpath.'/'.$fname);
                   3827:             return ($fullpath.'/'.$fname,$info[9]);
                   3828:         } else {
                   3829:             return $fullpath.'/'.$fname;
                   3830:         }
1.523     raeburn  3831:     }
1.995     raeburn  3832:     if ($subdir eq 'scantron') {
                   3833:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3834:     } else {
1.995     raeburn  3835:         $fname="$subdir/$fname";
                   3836:     }
1.1090    raeburn  3837:     if ($context eq 'coursedoc') {
1.638     albertel 3838: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3839: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3840:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3841:             return &finishuserfileupload($docuname,$docudom,
                   3842: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3843: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3844:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3845:         } else {
1.1172.2.21  raeburn  3846:             if ($env{'form.folder'}) {
                   3847:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3848:             }
1.638     albertel 3849:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3850: 				       $fname,$formname,$parser,
1.1095    raeburn  3851: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3852:         }
1.719     banghart 3853:     } elsif (defined($destuname)) {
                   3854:         my $docuname=$destuname;
                   3855:         my $docudom=$destudom;
1.860     raeburn  3856: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3857: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3858:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3859:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3860:     } else {
1.638     albertel 3861:         my $docuname=$env{'user.name'};
                   3862:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3863:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3864:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3865:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3866:         }
1.860     raeburn  3867: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3868: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3869:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3870:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3871:     }
1.271     www      3872: }
                   3873: 
                   3874: sub finishuserfileupload {
1.860     raeburn  3875:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3876:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3877:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3878:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3879:   
1.860     raeburn  3880:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3881:     $file=$fname;
                   3882:     if ($fname=~m|/|) {
                   3883:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3884: 	$path.=$fnamepath.'/';
                   3885:     }
1.259     www      3886:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3887:     my $count;
                   3888:     for ($count=4;$count<=$#parts;$count++) {
                   3889:         $filepath.="/$parts[$count]";
                   3890:         if ((-e $filepath)!=1) {
                   3891: 	    mkdir($filepath,0777);
                   3892:         }
                   3893:     }
1.984     neumanie 3894: 
1.258     www      3895: # Save the file
                   3896:     {
1.1172.2.96  raeburn  3897: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3898: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3899: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3900: 	    return '/adm/notfound.html';
                   3901: 	}
1.1090    raeburn  3902:         if ($context eq 'overwrite') {
1.1117    foxr     3903:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3904:             my $target = $filepath.'/'.$file;
                   3905:             if (-e $source) {
                   3906:                 my @info = stat($source);
                   3907:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3908:                     unless (&File::Copy::move($source,$target)) {
                   3909:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3910:                         return "Moving from $source failed";
                   3911:                     }
                   3912:                 } else {
                   3913:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3914:                 }
                   3915:             } else {
                   3916:                 return "Temporary file: $source missing";
                   3917:             }
                   3918:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3919: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3920: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3921: 	    return '/adm/notfound.html';
                   3922: 	}
1.570     albertel 3923: 	close(FH);
1.1051    raeburn  3924:         if ($resizewidth && $resizeheight) {
                   3925:             my $mm = new File::MMagic;
                   3926:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3927:             if ($mime_type =~ m{^image/}) {
                   3928: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3929:             }  
1.977     amueller 3930: 	}
1.258     www      3931:     }
1.1152    raeburn  3932:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3933:         if (ref($mimetype)) {
                   3934:             if ($$mimetype eq '') {
                   3935:                 my $mm = new File::MMagic;
                   3936:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3937:                 $$mimetype = $type;
                   3938:             }
                   3939:         }
                   3940:     }
1.1172.2.109  raeburn  3941:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3942:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3943:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3944:                                                        $allfiles,$codebase);
                   3945:             unless ($parse_result eq 'ok') {
                   3946:                 &logthis('Failed to parse '.$filepath.$file.
                   3947: 	   	         ' for embedded media: '.$parse_result); 
                   3948:             }
1.637     raeburn  3949:         }
1.1172.2.109  raeburn  3950:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3951:         my $format = $env{'form.scantron_format'};
                   3952:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3953:     }
1.860     raeburn  3954:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3955:         my $input = $filepath.'/'.$file;
                   3956:         my $output = $filepath.'/'.'tn-'.$file;
                   3957:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3958:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3959:         system({$args[0]} @args);
1.860     raeburn  3960:         if (-e $filepath.'/'.'tn-'.$file) {
                   3961:             $fetchthumb  = 1; 
                   3962:         }
                   3963:     }
1.858     raeburn  3964:  
1.259     www      3965: # Notify homeserver to grep it
                   3966: #
1.984     neumanie 3967:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3968:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3969:     if ($fetchresult eq 'ok') {
1.860     raeburn  3970:         if ($fetchthumb) {
                   3971:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3972:             if ($thumbresult ne 'ok') {
                   3973:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3974:                          $docuhome.': '.$thumbresult);
                   3975:             }
                   3976:         }
1.259     www      3977: #
1.258     www      3978: # Return the URL to it
1.494     albertel 3979:         return '/uploaded/'.$path.$file;
1.263     www      3980:     } else {
1.494     albertel 3981:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3982: 		 ': '.$fetchresult);
1.263     www      3983:         return '/adm/notfound.html';
1.858     raeburn  3984:     }
1.493     albertel 3985: }
                   3986: 
1.637     raeburn  3987: sub extract_embedded_items {
1.961     raeburn  3988:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3989:     my @state = ();
1.1164    raeburn  3990:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3991:     my %javafiles = (
                   3992:                       codebase => '',
                   3993:                       code => '',
                   3994:                       archive => ''
                   3995:                     );
                   3996:     my %mediafiles = (
                   3997:                       src => '',
                   3998:                       movie => '',
                   3999:                      );
1.648     raeburn  4000:     my $p;
                   4001:     if ($content) {
                   4002:         $p = HTML::LCParser->new($content);
                   4003:     } else {
1.961     raeburn  4004:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4005:     }
1.641     albertel 4006:     while (my $t=$p->get_token()) {
1.640     albertel 4007: 	if ($t->[0] eq 'S') {
                   4008: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4009: 	    push(@state, $tagname);
1.648     raeburn  4010:             if (lc($tagname) eq 'allow') {
                   4011:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4012:             }
1.640     albertel 4013: 	    if (lc($tagname) eq 'img') {
                   4014: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4015: 	    }
1.886     albertel 4016: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4017:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4018: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4019:                 }
1.886     albertel 4020: 	    }
1.645     raeburn  4021:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4022:                 my $src;
1.645     raeburn  4023:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4024:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4025:                 } else {
1.1164    raeburn  4026:                     if ($attr->{'src'} ne '') {
                   4027:                         $src = $attr->{'src'};
                   4028:                         &add_filetype($allfiles,$src,'src');
                   4029:                     }
                   4030:                 }
                   4031:                 my $text = $p->get_trimmed_text();
                   4032:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4033:                     my @swfargs = split(/,/,$1);
                   4034:                     foreach my $item (@swfargs) {
                   4035:                         $item =~ s/["']//g;
                   4036:                         $item =~ s/^\s+//;
                   4037:                         $item =~ s/\s+$//;
                   4038:                     }
                   4039:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4040:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4041:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4042:                         } else {
                   4043:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4044:                         }
                   4045:                     }
1.645     raeburn  4046:                 }
                   4047:             }
                   4048:             if (lc($tagname) eq 'link') {
                   4049:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4050:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4051:                 }
                   4052:             }
1.640     albertel 4053: 	    if (lc($tagname) eq 'object' ||
                   4054: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4055: 		foreach my $item (keys(%javafiles)) {
                   4056: 		    $javafiles{$item} = '';
                   4057: 		}
1.1164    raeburn  4058:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4059:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4060:                 }
1.640     albertel 4061: 	    }
                   4062: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4063: 		my $name = lc($attr->{'name'});
                   4064: 		foreach my $item (keys(%javafiles)) {
                   4065: 		    if ($name eq $item) {
                   4066: 			$javafiles{$item} = $attr->{'value'};
                   4067: 			last;
                   4068: 		    }
                   4069: 		}
1.1164    raeburn  4070:                 my $pathfrom;
1.640     albertel 4071: 		foreach my $item (keys(%mediafiles)) {
                   4072: 		    if ($name eq $item) {
1.1164    raeburn  4073:                         $pathfrom = $attr->{'value'};
                   4074:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4075: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4076: 			last;
                   4077: 		    }
                   4078: 		}
1.1164    raeburn  4079:                 if ($name eq 'flashvars') {
                   4080:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4081:                 }
                   4082:                 if ($pathfrom ne '') {
                   4083:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4084:                                          $pathfrom);
                   4085:                 }
1.640     albertel 4086: 	    }
                   4087: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4088: 		foreach my $item (keys(%javafiles)) {
                   4089: 		    if ($attr->{$item}) {
                   4090: 			$javafiles{$item} = $attr->{$item};
                   4091: 			last;
                   4092: 		    }
                   4093: 		}
                   4094: 		foreach my $item (keys(%mediafiles)) {
                   4095: 		    if ($attr->{$item}) {
                   4096: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4097: 			last;
                   4098: 		    }
                   4099: 		}
1.1164    raeburn  4100:                 if (lc($tagname) eq 'embed') {
                   4101:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4102:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4103:                                              $attr->{'src'});
                   4104:                     }
                   4105:                 }
1.640     albertel 4106: 	    }
1.1172.2.35  raeburn  4107:             if (lc($tagname) eq 'iframe') {
                   4108:                 my $src = $attr->{'src'} ;
                   4109:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4110:                     &add_filetype($allfiles,$src,'src');
                   4111:                 } elsif ($src =~ m{^/}) {
                   4112:                     if ($env{'request.course.id'}) {
                   4113:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4114:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4115:                         my $url = &hreflocation('',$fullpath);
                   4116:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4117:                             my $relpath = $1;
                   4118:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4119:                                 &add_filetype($allfiles,$1,'src');
                   4120:                             }
                   4121:                         }
                   4122:                     }
                   4123:                 }
                   4124:             }
1.1164    raeburn  4125:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4126:                 pop(@state);
1.1164    raeburn  4127:             }
1.640     albertel 4128: 	} elsif ($t->[0] eq 'E') {
                   4129: 	    my ($tagname) = ($t->[1]);
                   4130: 	    if ($javafiles{'codebase'} ne '') {
                   4131: 		$javafiles{'codebase'} .= '/';
                   4132: 	    }  
                   4133: 	    if (lc($tagname) eq 'applet' ||
                   4134: 		lc($tagname) eq 'object' ||
                   4135: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4136: 		) {
                   4137: 		foreach my $item (keys(%javafiles)) {
                   4138: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4139: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4140: 			&add_filetype($allfiles,$file,$item);
                   4141: 		    }
                   4142: 		}
                   4143: 	    } 
                   4144: 	    pop @state;
                   4145: 	}
                   4146:     }
1.1164    raeburn  4147:     foreach my $id (sort(keys(%flashvars))) {
                   4148:         if ($shockwave{$id} ne '') {
                   4149:             my @pairs = split(/\&/,$flashvars{$id});
                   4150:             foreach my $pair (@pairs) {
                   4151:                 my ($key,$value) = split(/\=/,$pair);
                   4152:                 if ($key eq 'thumb') {
                   4153:                     &add_filetype($allfiles,$value,$key);
                   4154:                 } elsif ($key eq 'content') {
                   4155:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4156:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4157:                     if ($ext ne '') {
                   4158:                         &add_filetype($allfiles,$path.$value,$ext);
                   4159:                     }
                   4160:                 }
                   4161:             }
                   4162:         }
                   4163:     }
1.637     raeburn  4164:     return 'ok';
                   4165: }
                   4166: 
1.639     albertel 4167: sub add_filetype {
                   4168:     my ($allfiles,$file,$type)=@_;
                   4169:     if (exists($allfiles->{$file})) {
                   4170: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4171: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4172: 	}
                   4173:     } else {
                   4174: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4175:     }
                   4176: }
                   4177: 
1.1164    raeburn  4178: sub embedded_dependency {
                   4179:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4180:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4181:         if (($identifier ne '') &&
                   4182:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4183:             ($pathfrom ne '')) {
                   4184:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4185:             foreach my $dep (@{$related->{$identifier}}) {
                   4186:                 &add_filetype($allfiles,$path.$dep,'object');
                   4187:             }
                   4188:         }
                   4189:     }
                   4190:     return;
                   4191: }
                   4192: 
1.1172.2.109  raeburn  4193: sub bubblesheet_converter {
                   4194:     my ($cdom,$fullpath,$config,$format) = @_;
                   4195:     if ((&domain($cdom) ne '') &&
                   4196:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4197:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4198:         my (%csvcols,%csvoptions);
                   4199:         if (ref($config->{'fields'}) eq 'HASH') {
                   4200:             %csvcols = %{$config->{'fields'}};
                   4201:         }
                   4202:         if (ref($config->{'options'}) eq 'HASH') {
                   4203:             %csvoptions = %{$config->{'options'}};
                   4204:         }
                   4205:         my %csvbynum = reverse(%csvcols);
                   4206:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4207:         if (keys(%scantronconf)) {
                   4208:             my %bynum = (
                   4209:                           $scantronconf{CODEstart} => 'CODEstart',
                   4210:                           $scantronconf{IDstart}   => 'IDstart',
                   4211:                           $scantronconf{PaperID}   => 'PaperID',
                   4212:                           $scantronconf{FirstName} => 'FirstName',
                   4213:                           $scantronconf{LastName}  => 'LastName',
                   4214:                           $scantronconf{Qstart}    => 'Qstart',
                   4215:                         );
                   4216:             my @ordered;
                   4217:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4218:                 push(@ordered,$bynum{$item});
                   4219:             }
                   4220:             my %mapstart = (
                   4221:                               CODEstart => 'CODE',
                   4222:                               IDstart   => 'ID',
                   4223:                               PaperID   => 'PaperID',
                   4224:                               FirstName => 'FirstName',
                   4225:                               LastName  => 'LastName',
                   4226:                               Qstart    => 'FirstQuestion',
                   4227:                            );
                   4228:             my %maplength = (
                   4229:                               CODEstart => 'CODElength',
                   4230:                               IDstart   => 'IDlength',
                   4231:                               PaperID   => 'PaperIDlength',
                   4232:                               FirstName => 'FirstNamelength',
                   4233:                               LastName  => 'LastNamelength',
                   4234:             );
                   4235:             if (open(my $fh,'<',$fullpath)) {
                   4236:                 my $output;
                   4237:                 my %lettdig = &letter_to_digits();
                   4238:                 my %diglett = reverse(%lettdig);
                   4239:                 my $numletts = scalar(keys(%lettdig));
                   4240:                 my $num = 0;
                   4241:                 while (my $line=<$fh>) {
                   4242:                     $num ++;
                   4243:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4244:                     $line =~ s{[\r\n]+$}{};
                   4245:                     my %found;
                   4246:                     my @values = split(/,/,$line);
                   4247:                     my ($qstart,$record);
                   4248:                     for (my $i=0; $i<@values; $i++) {
                   4249:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4250:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4251:                             if ($values[$i] eq '') {
                   4252:                                 $values[$i] = $scantronconf{'Qoff'};
                   4253:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4254:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4255:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4256:                                 }
                   4257:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4258:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4259:                                     $values[$i] = $diglett{$values[$i]};
                   4260:                                 }
                   4261:                             } else {
                   4262:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4263:                                     my $digit;
                   4264:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4265:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4266:                                         if ($values[$i] eq 'J') {
                   4267:                                             $digit += $numletts;
                   4268:                                         }
                   4269:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4270:                                         $digit = $values[$i]-1;
                   4271:                                         if ($values[$i] eq '0') {
                   4272:                                             $digit += $numletts;
                   4273:                                         }
                   4274:                                     }
                   4275:                                     my $qval='';
                   4276:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4277:                                         if ($j == $digit) {
                   4278:                                             $qval .= $scantronconf{'Qon'};
                   4279:                                         } else {
                   4280:                                             $qval .= $scantronconf{'Qoff'};
                   4281:                                         }
                   4282:                                     }
                   4283:                                     $values[$i] = $qval;
                   4284:                                 }
                   4285:                             }
                   4286:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4287:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4288:                             }
                   4289:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4290:                             if ($numblank > 0) {
                   4291:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4292:                             }
                   4293:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4294:                                 $qstart = $i;
                   4295:                                 $found{$csvbynum{$i}} = $values[$i];
                   4296:                             } else {
                   4297:                                 $found{'FirstQuestion'} .= $values[$i];
                   4298:                             }
                   4299:                         } elsif (exists($csvbynum{$i})) {
                   4300:                             if ($csvoptions{'rem'}) {
                   4301:                                 $values[$i] =~ s/^\s+//;
                   4302:                             }
                   4303:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4304:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4305:                                     $values[$i] = '0'.$values[$i];
                   4306:                                 }
                   4307:                             }
                   4308:                             $found{$csvbynum{$i}} = $values[$i];
                   4309:                         }
                   4310:                     }
                   4311:                     foreach my $item (@ordered) {
                   4312:                         my $currlength = 1+length($record);
                   4313:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4314:                         if ($numspaces > 0) {
                   4315:                             $record .= (' ' x $numspaces);
                   4316:                         }
                   4317:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4318:                             unless ($item eq 'Qstart') {
                   4319:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4320:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4321:                                 }
                   4322:                             }
                   4323:                             $record .= $found{$mapstart{$item}};
                   4324:                         }
                   4325:                     }
                   4326:                     $output .= "$record\n";
                   4327:                 }
                   4328:                 close($fh);
                   4329:                 if ($output) {
                   4330:                     if (open(my $fh,'>',$fullpath)) {
                   4331:                         print $fh $output;
                   4332:                         close($fh);
                   4333:                     }
                   4334:                 }
                   4335:             }
                   4336:         }
                   4337:         return;
                   4338:     }
                   4339: }
                   4340: 
                   4341: sub letter_to_digits {
                   4342:     my %lettdig = (
                   4343:                     A => 1,
                   4344:                     B => 2,
                   4345:                     C => 3,
                   4346:                     D => 4,
                   4347:                     E => 5,
                   4348:                     F => 6,
                   4349:                     G => 7,
                   4350:                     H => 8,
                   4351:                     I => 9,
                   4352:                     J => 0,
                   4353:                   );
                   4354:     return %lettdig;
                   4355: }
                   4356: 
                   4357: sub get_scantron_config {
                   4358:     my ($which,$cdom) = @_;
                   4359:     my @lines = &get_scantronformat_file($cdom);
                   4360:     my %config;
                   4361:     #FIXME probably should move to XML it has already gotten a bit much now
                   4362:     foreach my $line (@lines) {
                   4363:         my ($name,$descrip)=split(/:/,$line);
                   4364:         if ($name ne $which ) { next; }
                   4365:         chomp($line);
                   4366:         my @config=split(/:/,$line);
                   4367:         $config{'name'}=$config[0];
                   4368:         $config{'description'}=$config[1];
                   4369:         $config{'CODElocation'}=$config[2];
                   4370:         $config{'CODEstart'}=$config[3];
                   4371:         $config{'CODElength'}=$config[4];
                   4372:         $config{'IDstart'}=$config[5];
                   4373:         $config{'IDlength'}=$config[6];
                   4374:         $config{'Qstart'}=$config[7];
                   4375:         $config{'Qlength'}=$config[8];
                   4376:         $config{'Qoff'}=$config[9];
                   4377:         $config{'Qon'}=$config[10];
                   4378:         $config{'PaperID'}=$config[11];
                   4379:         $config{'PaperIDlength'}=$config[12];
                   4380:         $config{'FirstName'}=$config[13];
                   4381:         $config{'FirstNamelength'}=$config[14];
                   4382:         $config{'LastName'}=$config[15];
                   4383:         $config{'LastNamelength'}=$config[16];
                   4384:         $config{'BubblesPerRow'}=$config[17];
                   4385:         last;
                   4386:     }
                   4387:     return %config;
                   4388: }
                   4389: 
                   4390: sub get_scantronformat_file {
                   4391:     my ($cdom) = @_;
                   4392:     if ($cdom eq '') {
                   4393:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4394:     }
                   4395:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4396:     my $gottab = 0;
                   4397:     my @lines;
                   4398:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4399:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4400:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4401:             if ($formatfile ne '-1') {
                   4402:                 @lines = split("\n",$formatfile,-1);
                   4403:                 $gottab = 1;
                   4404:             }
                   4405:         }
                   4406:     }
                   4407:     if (!$gottab) {
                   4408:         my $confname = $cdom.'-domainconfig';
                   4409:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4410:         my $formatfile = &getfile($default);
                   4411:         if ($formatfile ne '-1') {
                   4412:             @lines = split("\n",$formatfile,-1);
                   4413:             $gottab = 1;
                   4414:         }
                   4415:     }
                   4416:     if (!$gottab) {
                   4417:         my @domains = &current_machine_domains();
                   4418:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4419:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4420:                 @lines = <$fh>;
                   4421:                 close($fh);
                   4422:             }
                   4423:         } else {
                   4424:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4425:                 @lines = <$fh>;
                   4426:                 close($fh);
                   4427:             }
                   4428:         }
                   4429:     }
                   4430:     return @lines;
                   4431: }
                   4432: 
1.493     albertel 4433: sub removeuploadedurl {
1.984     neumanie 4434:     my ($url)=@_;	
                   4435:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4436:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4437: }
                   4438: 
                   4439: sub removeuserfile {
                   4440:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4441:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4442:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4443:     if ($result eq 'ok') {	
1.798     raeburn  4444:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4445:             my $metafile = $fname.'.meta';
                   4446:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4447: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4448:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4449:             my $sqlresult = 
1.823     albertel 4450:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4451:                                         'portfolio_metadata',$group,
                   4452:                                         'delete');
1.798     raeburn  4453:         }
                   4454:     }
                   4455:     return $result;
1.257     www      4456: }
1.15      www      4457: 
1.530     albertel 4458: sub mkdiruserfile {
                   4459:     my ($docuname,$docudom,$dir)=@_;
                   4460:     my $home=&homeserver($docuname,$docudom);
                   4461:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4462: }
                   4463: 
1.531     albertel 4464: sub renameuserfile {
                   4465:     my ($docuname,$docudom,$old,$new)=@_;
                   4466:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4467:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4468:                         &escape("$old").':'.&escape("$new"),$home);
                   4469:     if ($result eq 'ok') {
                   4470:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4471:             my $oldmeta = $old.'.meta';
                   4472:             my $newmeta = $new.'.meta';
                   4473:             my $metaresult = 
                   4474:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4475: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4476:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4477:             my $sqlresult = 
1.823     albertel 4478:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4479:                                         'portfolio_metadata',$group,
                   4480:                                         'delete');
1.798     raeburn  4481:         }
                   4482:     }
                   4483:     return $result;
1.531     albertel 4484: }
                   4485: 
1.14      www      4486: # ------------------------------------------------------------------------- Log
                   4487: 
                   4488: sub log {
                   4489:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4490:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4491: }
                   4492: 
                   4493: # ------------------------------------------------------------------ Course Log
1.352     www      4494: #
                   4495: # This routine flushes several buffers of non-mission-critical nature
                   4496: #
1.157     www      4497: 
                   4498: sub flushcourselogs {
1.352     www      4499:     &logthis('Flushing log buffers');
                   4500: #
                   4501: # course logs
                   4502: # This is a log of all transactions in a course, which can be used
                   4503: # for data mining purposes
                   4504: #
                   4505: # It also collects the courseid database, which lists last transaction
                   4506: # times and course titles for all courseids
                   4507: #
                   4508:     my %courseidbuffer=();
1.921     raeburn  4509:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4510:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4511: 		          &escape($courselogs{$crsid}),
                   4512: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4513: 	    delete $courselogs{$crsid};
                   4514:         } else {
                   4515:             &logthis('Failed to flush log buffer for '.$crsid);
                   4516:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4517:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4518:                         " exceeded maximum size, deleting.</font>");
                   4519:                delete $courselogs{$crsid};
                   4520:             }
1.352     www      4521:         }
1.920     raeburn  4522:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4523:             'description' => $coursedescrbuf{$crsid},
                   4524:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4525:             'type'        => $coursetypebuf{$crsid},
                   4526:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4527:         };
1.191     harris41 4528:     }
1.352     www      4529: #
                   4530: # Write course id database (reverse lookup) to homeserver of courses 
                   4531: # Is used in pickcourse
                   4532: #
1.840     albertel 4533:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4534:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4535:                                     $courseidbuffer{$crs_home},
                   4536:                                     $crs_home,'timeonly');
1.352     www      4537:     }
                   4538: #
                   4539: # File accesses
                   4540: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4541: #
1.449     matthew  4542:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4543:         if ($entry =~ /___count$/) {
                   4544:             my ($dom,$name);
1.807     albertel 4545:             ($dom,$name,undef)=
1.811     albertel 4546: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4547:             if (! defined($dom) || $dom eq '' || 
                   4548:                 ! defined($name) || $name eq '') {
1.620     albertel 4549:                 my $cid = $env{'request.course.id'};
                   4550:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4551:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4552:             }
1.450     matthew  4553:             my $value = $accesshash{$entry};
                   4554:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4555:             my %temphash=($url => $value);
1.449     matthew  4556:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4557:             if ($result eq 'ok') {
                   4558:                 delete $accesshash{$entry};
                   4559:             }
                   4560:         } else {
1.811     albertel 4561:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4562:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4563:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4564:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4565:                 delete $accesshash{$entry};
                   4566:             }
1.185     www      4567:         }
1.191     harris41 4568:     }
1.352     www      4569: #
                   4570: # Roles
                   4571: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4572: #
1.800     albertel 4573:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4574:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4575: 	    split(/\:/,$entry);
                   4576:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4577:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4578:                 $rudom,$runame) eq 'ok') {
                   4579: 	    delete $userrolehash{$entry};
                   4580:         }
                   4581:     }
1.662     raeburn  4582: #
1.1172.2.90  raeburn  4583: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4584: #
                   4585:     my %domrolebuffer = ();
1.1000    raeburn  4586:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4587:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4588:         if ($domrolebuffer{$rudom}) {
                   4589:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4590:                       '='.&escape($domainrolehash{$entry});
                   4591:         } else {
                   4592:             $domrolebuffer{$rudom}.=&escape($entry).
                   4593:                       '='.&escape($domainrolehash{$entry});
                   4594:         }
                   4595:         delete $domainrolehash{$entry};
                   4596:     }
                   4597:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4598:         my %servers;
                   4599:         if (defined(&domain($dom,'primary'))) {
                   4600:             my $primary=&domain($dom,'primary');
                   4601:             my $hostname=&hostname($primary);
                   4602:             $servers{$primary} = $hostname;
                   4603:         } else {
                   4604:             %servers = &get_servers($dom,'library');
                   4605:         }
1.841     albertel 4606: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4607: 	    if (&reply('domroleput:'.$dom.':'.
                   4608: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4609: 	        last;
                   4610: 	    } else {
1.841     albertel 4611: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4612: 	    }
1.662     raeburn  4613:         }
                   4614:     }
1.186     www      4615:     $dumpcount++;
1.157     www      4616: }
                   4617: 
                   4618: sub courselog {
                   4619:     my $what=shift;
1.158     www      4620:     $what=time.':'.$what;
1.620     albertel 4621:     unless ($env{'request.course.id'}) { return ''; }
                   4622:     $coursedombuf{$env{'request.course.id'}}=
                   4623:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4624:     $coursenumbuf{$env{'request.course.id'}}=
                   4625:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4626:     $coursehombuf{$env{'request.course.id'}}=
                   4627:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4628:     $coursedescrbuf{$env{'request.course.id'}}=
                   4629:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4630:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4631:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4632:     $courseownerbuf{$env{'request.course.id'}}=
                   4633:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4634:     $coursetypebuf{$env{'request.course.id'}}=
                   4635:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4636:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4637: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4638:     } else {
1.620     albertel 4639: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4640:     }
1.620     albertel 4641:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4642: 	&flushcourselogs();
                   4643:     }
1.158     www      4644: }
                   4645: 
                   4646: sub courseacclog {
                   4647:     my $fnsymb=shift;
1.620     albertel 4648:     unless ($env{'request.course.id'}) { return ''; }
                   4649:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4650:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4651:         $what.=':POST';
1.583     matthew  4652:         # FIXME: Probably ought to escape things....
1.800     albertel 4653: 	foreach my $key (keys(%env)) {
                   4654:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4655:                 my $formitem = $1;
                   4656:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4657:                     $what.=':'.$formitem.'='.$env{$key};
                   4658:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4659:                     $what.=':'.$formitem.'='.$env{$key};
                   4660:                 }
1.158     www      4661:             }
1.191     harris41 4662:         }
1.583     matthew  4663:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4664:         # FIXME: We should not be depending on a form parameter that someone
                   4665:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4666:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4667:             $what.= ':POST';
                   4668:             # FIXME: Probably ought to escape things....
                   4669:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4670:                                  'crsdiscuss') {
1.620     albertel 4671:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4672:             }
                   4673:         }
1.158     www      4674:     }
                   4675:     &courselog($what);
1.149     www      4676: }
                   4677: 
1.185     www      4678: sub countacc {
                   4679:     my $url=&declutter(shift);
1.458     matthew  4680:     return if (! defined($url) || $url eq '');
1.620     albertel 4681:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4682: #
                   4683: # Mark that this url was used in this course
                   4684: #
1.620     albertel 4685:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4686: #
                   4687: # Increase the access count for this resource in this child process
                   4688: #
1.281     www      4689:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4690:     $accesshash{$key}++;
1.185     www      4691: }
1.349     www      4692: 
1.361     www      4693: sub linklog {
                   4694:     my ($from,$to)=@_;
                   4695:     $from=&declutter($from);
                   4696:     $to=&declutter($to);
                   4697:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4698:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4699: }
1.1160    www      4700: 
                   4701: sub statslog {
                   4702:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4703:     if ($users<2) { return; }
                   4704:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4705:             'course'       => $env{'request.course.id'},
                   4706:             'sections'     => '"all"',
                   4707:             'num_students' => $users,
                   4708:             'part'         => $part,
                   4709:             'symb'         => $symb,
                   4710:             'mean_tries'   => $av_attempts,
                   4711:             'deg_of_diff'  => $degdiff});
                   4712:     foreach my $key (keys(%dynstore)) {
                   4713:         $accesshash{$key}=$dynstore{$key};
                   4714:     }
                   4715: }
1.361     www      4716:   
1.349     www      4717: sub userrolelog {
                   4718:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4719:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4720:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4721:        $userrolehash
                   4722:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4723:                     =$tend.':'.$tstart;
1.662     raeburn  4724:     }
1.1169    droeschl 4725:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4726:        $userrolehash
                   4727:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4728:                     =$tend.':'.$tstart;
                   4729:     }
1.1172.2.90  raeburn  4730:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4731:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4732:        $domainrolehash
                   4733:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4734:                     = $tend.':'.$tstart;
                   4735:     }
1.351     www      4736: }
                   4737: 
1.957     raeburn  4738: sub courserolelog {
                   4739:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4740:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4741:         my $cdom = $1;
                   4742:         my $cnum = $2;
                   4743:         my $sec = $3;
                   4744:         my $namespace = 'rolelog';
                   4745:         my %storehash = (
                   4746:                            role    => $trole,
                   4747:                            start   => $tstart,
                   4748:                            end     => $tend,
                   4749:                            selfenroll => $selfenroll,
                   4750:                            context    => $context,
                   4751:                         );
                   4752:         if ($trole eq 'gr') {
                   4753:             $namespace = 'groupslog';
                   4754:             $storehash{'group'} = $sec;
                   4755:         } else {
                   4756:             $storehash{'section'} = $sec;
                   4757:         }
                   4758:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4759:                    $domain,$cnum,$cdom);
                   4760:         if (($trole ne 'st') || ($sec ne '')) {
                   4761:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4762:         }
                   4763:     }
                   4764:     return;
                   4765: }
                   4766: 
1.1172.2.9  raeburn  4767: sub domainrolelog {
                   4768:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4769:     if ($area =~ m{^/($match_domain)/$}) {
                   4770:         my $cdom = $1;
                   4771:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4772:         my $namespace = 'rolelog';
                   4773:         my %storehash = (
                   4774:                            role    => $trole,
                   4775:                            start   => $tstart,
                   4776:                            end     => $tend,
                   4777:                            context => $context,
                   4778:                         );
                   4779:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4780:                    $domain,$domconfiguser,$cdom);
                   4781:     }
                   4782:     return;
                   4783: 
                   4784: }
                   4785: 
                   4786: sub coauthorrolelog {
                   4787:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4788:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4789:         my $audom = $1;
                   4790:         my $auname = $2;
                   4791:         my $namespace = 'rolelog';
                   4792:         my %storehash = (
                   4793:                            role    => $trole,
                   4794:                            start   => $tstart,
                   4795:                            end     => $tend,
                   4796:                            context => $context,
                   4797:                         );
                   4798:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4799:                    $domain,$auname,$audom);
                   4800:     }
                   4801:     return;
                   4802: }
                   4803: 
1.351     www      4804: sub get_course_adv_roles {
1.948     raeburn  4805:     my ($cid,$codes) = @_;
1.620     albertel 4806:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4807:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4808:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4809:     my %nothide=();
1.800     albertel 4810:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4811:         if ($user !~ /:/) {
                   4812: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4813:         } else {
                   4814:             $nothide{$user}=1;
                   4815:         }
1.470     www      4816:     }
1.1172.2.23  raeburn  4817:     my @possdoms = ($coursehash{'domain'});
                   4818:     if ($coursehash{'checkforpriv'}) {
                   4819:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4820:     }
1.351     www      4821:     my %returnhash=();
                   4822:     my %dumphash=
                   4823:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4824:     my $now=time;
1.997     raeburn  4825:     my %privileged;
1.1000    raeburn  4826:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4827: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4828:         if (($tstart) && ($tstart<0)) { next; }
                   4829:         if (($tend) && ($tend<$now)) { next; }
                   4830:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4831:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4832: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4833:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4834:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4835: 	if ($role eq 'cr') { next; }
1.948     raeburn  4836:         if ($codes) {
                   4837:             if ($section) { $role .= ':'.$section; }
                   4838:             if ($returnhash{$role}) {
                   4839:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4840:             } else {
                   4841:                 $returnhash{$role}=$username.':'.$domain;
                   4842:             }
1.351     www      4843:         } else {
1.988     raeburn  4844:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4845:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4846:             if ($returnhash{$key}) {
                   4847: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4848:             } else {
                   4849:                 $returnhash{$key}=$username.':'.$domain;
                   4850:             }
1.351     www      4851:         }
1.948     raeburn  4852:     }
1.400     www      4853:     return %returnhash;
                   4854: }
                   4855: 
                   4856: sub get_my_roles {
1.937     raeburn  4857:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4858:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4859:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4860:     my (%dumphash,%nothide);
1.1086    raeburn  4861:     if ($context eq 'userroles') {
1.1166    raeburn  4862:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4863:     } else {
1.1172.2.23  raeburn  4864:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4865:         if ($hidepriv) {
                   4866:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4867:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4868:                 if ($user !~ /:/) {
                   4869:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4870:                 } else {
                   4871:                     $nothide{$user} = 1;
                   4872:                 }
                   4873:             }
                   4874:         }
1.858     raeburn  4875:     }
1.400     www      4876:     my %returnhash=();
                   4877:     my $now=time;
1.999     raeburn  4878:     my %privileged;
1.800     albertel 4879:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4880:         my ($role,$tend,$tstart);
                   4881:         if ($context eq 'userroles') {
1.1149    raeburn  4882:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4883: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4884:         } else {
                   4885:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4886:         }
1.400     www      4887:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4888:         my $status = 'active';
1.939     raeburn  4889:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4890:             $status = 'previous';
                   4891:         } 
                   4892:         if (($tstart) && ($now<$tstart)) {
                   4893:             $status = 'future';
                   4894:         }
                   4895:         if (ref($types) eq 'ARRAY') {
                   4896:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4897:                 next;
                   4898:             } 
                   4899:         } else {
                   4900:             if ($status ne 'active') {
                   4901:                 next;
                   4902:             }
                   4903:         }
1.867     raeburn  4904:         my ($rolecode,$username,$domain,$section,$area);
                   4905:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4906:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4907:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4908:         } else {
                   4909:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4910:         }
1.832     raeburn  4911:         if (ref($roledoms) eq 'ARRAY') {
                   4912:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4913:                 next;
                   4914:             }
                   4915:         }
                   4916:         if (ref($roles) eq 'ARRAY') {
                   4917:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4918:                 if ($role =~ /^cr\//) {
                   4919:                     if (!grep(/^cr$/,@{$roles})) {
                   4920:                         next;
                   4921:                     }
1.1104    raeburn  4922:                 } elsif ($role =~ /^gr\//) {
                   4923:                     if (!grep(/^gr$/,@{$roles})) {
                   4924:                         next;
                   4925:                     }
1.922     raeburn  4926:                 } else {
                   4927:                     next;
                   4928:                 }
1.832     raeburn  4929:             }
1.867     raeburn  4930:         }
1.937     raeburn  4931:         if ($hidepriv) {
1.1172.2.23  raeburn  4932:             my @privroles = ('dc','su');
1.999     raeburn  4933:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4934:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4935:             } else {
1.1172.2.23  raeburn  4936:                 my $possdoms = [$domain];
                   4937:                 if (ref($roledoms) eq 'ARRAY') {
                   4938:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4939:                 }
1.1172.2.23  raeburn  4940:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4941:                     if (!$nothide{$username.':'.$domain}) {
                   4942:                         next;
                   4943:                     }
                   4944:                 }
1.937     raeburn  4945:             }
                   4946:         }
1.933     raeburn  4947:         if ($withsec) {
                   4948:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4949:                 $tstart.':'.$tend;
                   4950:         } else {
                   4951:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4952:         }
1.832     raeburn  4953:     }
1.373     www      4954:     return %returnhash;
1.399     www      4955: }
                   4956: 
1.1172.2.89  raeburn  4957: sub get_all_adhocroles {
                   4958:     my ($dom) = @_;
                   4959:     my @roles_by_num = ();
                   4960:     my %domdefaults = &get_domain_defaults($dom);
                   4961:     my (%description,%access_in_dom,%access_info);
                   4962:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4963:         my $count = 0;
                   4964:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4965:         my %ordered;
                   4966:         foreach my $role (sort(keys(%domcurrent))) {
                   4967:             my ($order,$desc,$access_in_dom);
                   4968:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4969:                 $order = $domcurrent{$role}{'order'};
                   4970:                 $desc = $domcurrent{$role}{'desc'};
                   4971:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4972:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4973:             }
                   4974:             if ($order eq '') {
                   4975:                 $order = $count;
                   4976:             }
                   4977:             $ordered{$order} = $role;
                   4978:             if ($desc ne '') {
                   4979:                 $description{$role} = $desc;
                   4980:             } else {
                   4981:                 $description{$role}= $role;
                   4982:             }
                   4983:             $count++;
                   4984:         }
                   4985:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4986:             push(@roles_by_num,$ordered{$item});
                   4987:         }
                   4988:     }
                   4989:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4990: }
                   4991: 
                   4992: sub get_my_adhocroles {
                   4993:     my ($cid,$checkreg) = @_;
                   4994:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4995:     if ($env{'request.course.id'} eq $cid) {
                   4996:         $cdom = $env{'course.'.$cid.'.domain'};
                   4997:         $cnum = $env{'course.'.$cid.'.num'};
                   4998:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4999:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5000:         $cdom = $1;
                   5001:         $cnum = $2;
                   5002:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5003:                                      $cdom,$cnum);
                   5004:     }
                   5005:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5006:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5007:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5008:         if ($rosterhash{$user} ne '') {
                   5009:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5010:             return ([],{}) if ($type eq 'auto');
                   5011:         }
                   5012:     }
                   5013:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5014:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5015:             my $then=$env{'user.login.time'};
                   5016:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5017:             if (!$update) {
                   5018:                 $update = $then;
                   5019:             }
                   5020:             my @liveroles;
                   5021:             foreach my $role ('dh','da') {
                   5022:                 if ($env{"user.role.$role./$cdom/"}) {
                   5023:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5024:                     my $limit = $update;
                   5025:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5026:                         $limit = $then;
                   5027:                     }
                   5028:                     my $activerole = 1;
                   5029:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5030:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5031:                     if ($activerole) {
                   5032:                         push(@liveroles,$role);
                   5033:                     }
                   5034:                 }
                   5035:             }
                   5036:             if (@liveroles) {
1.1172.2.89  raeburn  5037:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5038:                     my ($accessref,$accessinfo,%access_in_dom);
                   5039:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5040:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5041:                         if (@{$roles_by_num}) {
                   5042:                             my %settings;
                   5043:                             if ($env{'request.course.id'} eq $cid) {
                   5044:                                 foreach my $envkey (keys(%env)) {
                   5045:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5046:                                         $settings{$1} = $env{$envkey};
                   5047:                                     }
                   5048:                                 }
                   5049:                             } else {
                   5050:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5051:                             }
                   5052:                             my %setincrs;
                   5053:                             if ($settings{'internal.adhocaccess'}) {
                   5054:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5055:                             }
                   5056:                             my @statuses;
                   5057:                             if ($env{'environment.inststatus'}) {
                   5058:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5059:                             }
                   5060:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5061:                             if (ref($accessref) eq 'HASH') {
                   5062:                                 %access_in_dom = %{$accessref};
                   5063:                             }
                   5064:                             foreach my $role (@{$roles_by_num}) {
                   5065:                                 my ($curraccess,@okstatus,@personnel);
                   5066:                                 if ($setincrs{$role}) {
                   5067:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5068:                                     if ($curraccess eq 'status') {
                   5069:                                         @okstatus = split(/\&/,$rest);
                   5070:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5071:                                         @personnel = split(/\&/,$rest);
                   5072:                                     }
                   5073:                                 } else {
                   5074:                                     $curraccess = $access_in_dom{$role};
                   5075:                                     if (ref($accessinfo) eq 'HASH') {
                   5076:                                         if ($curraccess eq 'status') {
                   5077:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5078:                                                 @okstatus = @{$accessinfo->{$role}};
                   5079:                                             }
                   5080:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5081:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5082:                                                 @personnel = @{$accessinfo->{$role}};
                   5083:                                             }
                   5084:                                         }
                   5085:                                     }
                   5086:                                 }
                   5087:                                 if ($curraccess eq 'none') {
                   5088:                                     next;
                   5089:                                 } elsif ($curraccess eq 'all') {
                   5090:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5091:                                 } elsif ($curraccess eq 'dh') {
                   5092:                                     if (grep(/^dh$/,@liveroles)) {
                   5093:                                         push(@possroles,$role);
                   5094:                                     } else {
                   5095:                                         next;
                   5096:                                     }
                   5097:                                 } elsif ($curraccess eq 'da') {
                   5098:                                     if (grep(/^da$/,@liveroles)) {
                   5099:                                         push(@possroles,$role);
                   5100:                                     } else {
                   5101:                                         next;
                   5102:                                     }
1.1172.2.89  raeburn  5103:                                 } elsif ($curraccess eq 'status') {
                   5104:                                     if (@okstatus) {
                   5105:                                         if (!@statuses) {
                   5106:                                             if (grep(/^default$/,@okstatus)) {
                   5107:                                                 push(@possroles,$role);
                   5108:                                             }
                   5109:                                         } else {
                   5110:                                             foreach my $status (@okstatus) {
                   5111:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5112:                                                     push(@possroles,$role);
                   5113:                                                     last;
                   5114:                                                 }
                   5115:                                             }
                   5116:                                         }
                   5117:                                     }
                   5118:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5119:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5120:                                         if ($curraccess eq 'exc') {
                   5121:                                             push(@possroles,$role);
                   5122:                                         }
                   5123:                                     } elsif ($curraccess eq 'inc') {
                   5124:                                         push(@possroles,$role);
                   5125:                                     }
                   5126:                                 }
                   5127:                             }
                   5128:                         }
                   5129:                     }
                   5130:                 }
                   5131:             }
                   5132:         }
                   5133:     }
                   5134:     unless (ref($description) eq 'HASH') {
                   5135:         if (ref($roles_by_num) eq 'ARRAY') {
                   5136:             my %desc;
                   5137:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5138:             $description = \%desc;
                   5139:         } else {
                   5140:             $description = {};
                   5141:         }
                   5142:     }
                   5143:     return (\@possroles,$description);
                   5144: }
                   5145: 
1.399     www      5146: # ----------------------------------------------------- Frontpage Announcements
                   5147: #
                   5148: #
                   5149: 
                   5150: sub postannounce {
                   5151:     my ($server,$text)=@_;
1.844     albertel 5152:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5153:     unless ($text=~/\w/) { $text=''; }
                   5154:     return &reply('setannounce:'.&escape($text),$server);
                   5155: }
                   5156: 
                   5157: sub getannounce {
1.448     albertel 5158: 
1.1172.2.96  raeburn  5159:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5160: 	my $announcement='';
1.800     albertel 5161: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5162: 	close($fh);
1.399     www      5163: 	if ($announcement=~/\w/) { 
                   5164: 	    return 
                   5165:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5166:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5167: 	} else {
                   5168: 	    return '';
                   5169: 	}
                   5170:     } else {
                   5171: 	return '';
                   5172:     }
1.351     www      5173: }
1.353     www      5174: 
                   5175: # ---------------------------------------------------------- Course ID routines
                   5176: # Deal with domain's nohist_courseid.db files
                   5177: #
                   5178: 
                   5179: sub courseidput {
1.921     raeburn  5180:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5181:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5182:     my $outcome;
                   5183:     if ($caller eq 'timeonly') {
                   5184:         my $cids = '';
                   5185:         foreach my $item (keys(%$storehash)) {
                   5186:             $cids.=&escape($item).'&';
                   5187:         }
                   5188:         $cids=~s/\&$//;
                   5189:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5190:                           $coursehome);       
                   5191:     } else {
                   5192:         my $items = '';
                   5193:         foreach my $item (keys(%$storehash)) {
                   5194:             $items.= &escape($item).'='.
                   5195:                      &freeze_escape($$storehash{$item}).'&';
                   5196:         }
                   5197:         $items=~s/\&$//;
                   5198:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5199:                           $coursehome);
1.918     raeburn  5200:     }
                   5201:     if ($outcome eq 'unknown_cmd') {
                   5202:         my $what;
                   5203:         foreach my $cid (keys(%$storehash)) {
                   5204:             $what .= &escape($cid).'=';
1.921     raeburn  5205:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5206:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5207:             }
                   5208:             $what =~ s/\:$/&/;
                   5209:         }
                   5210:         $what =~ s/\&$//;  
                   5211:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5212:     } else {
                   5213:         return $outcome;
                   5214:     }
1.353     www      5215: }
                   5216: 
                   5217: sub courseiddump {
1.921     raeburn  5218:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5219:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5220:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5221:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5222:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5223:     my $as_hash = 1;
                   5224:     my %returnhash;
                   5225:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5226:     my %libserv = &all_library();
                   5227:     foreach my $tryserver (keys(%libserv)) {
                   5228:         if ( (  $hostidflag == 1 
                   5229: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5230: 	     || (!defined($hostidflag)) ) {
                   5231: 
1.918     raeburn  5232: 	    if (($domfilter eq '') ||
                   5233: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5234:                 my $rep;
                   5235:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5236:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5237:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5238:                                 &escape($descfilter), &escape($instcodefilter),
                   5239:                                 &escape($ownerfilter), &escape($coursefilter),
                   5240:                                 &escape($typefilter), &escape($regexp_ok),
                   5241:                                 $as_hash, &escape($selfenrollonly),
                   5242:                                 &escape($catfilter), $showhidden, $caller,
                   5243:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5244:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5245:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5246:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5247:                 } else {
                   5248:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5249:                              $sincefilter.':'.&escape($descfilter).':'.
                   5250:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5251:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5252:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5253:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5254:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5255:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5256:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5257:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5258:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5259:                 }
                   5260: 
1.918     raeburn  5261:                 my @pairs=split(/\&/,$rep);
                   5262:                 foreach my $item (@pairs) {
                   5263:                     my ($key,$value)=split(/\=/,$item,2);
                   5264:                     $key = &unescape($key);
                   5265:                     next if ($key =~ /^error: 2 /);
                   5266:                     my $result = &thaw_unescape($value);
                   5267:                     if (ref($result) eq 'HASH') {
                   5268:                         $returnhash{$key}=$result;
                   5269:                     } else {
1.921     raeburn  5270:                         my @responses = split(/:/,$value);
                   5271:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5272:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5273:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5274:                         }
1.1008    raeburn  5275:                     }
1.353     www      5276:                 }
                   5277:             }
                   5278:         }
                   5279:     }
                   5280:     return %returnhash;
                   5281: }
                   5282: 
1.1055    raeburn  5283: sub courselastaccess {
                   5284:     my ($cdom,$cnum,$hostidref) = @_;
                   5285:     my %returnhash;
                   5286:     if ($cdom && $cnum) {
                   5287:         my $chome = &homeserver($cnum,$cdom);
                   5288:         if ($chome ne 'no_host') {
                   5289:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5290:             &extract_lastaccess(\%returnhash,$rep);
                   5291:         }
                   5292:     } else {
                   5293:         if (!$cdom) { $cdom=''; }
                   5294:         my %libserv = &all_library();
                   5295:         foreach my $tryserver (keys(%libserv)) {
                   5296:             if (ref($hostidref) eq 'ARRAY') {
                   5297:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5298:             } 
                   5299:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5300:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5301:                 &extract_lastaccess(\%returnhash,$rep);
                   5302:             }
                   5303:         }
                   5304:     }
                   5305:     return %returnhash;
                   5306: }
                   5307: 
                   5308: sub extract_lastaccess {
                   5309:     my ($returnhash,$rep) = @_;
                   5310:     if (ref($returnhash) eq 'HASH') {
                   5311:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5312:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5313:                  $rep eq '') {
                   5314:             my @pairs=split(/\&/,$rep);
                   5315:             foreach my $item (@pairs) {
                   5316:                 my ($key,$value)=split(/\=/,$item,2);
                   5317:                 $key = &unescape($key);
                   5318:                 next if ($key =~ /^error: 2 /);
                   5319:                 $returnhash->{$key} = &thaw_unescape($value);
                   5320:             }
                   5321:         }
                   5322:     }
                   5323:     return;
                   5324: }
                   5325: 
1.658     raeburn  5326: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5327: 
                   5328: sub dcmailput {
1.685     raeburn  5329:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5330:     my $status = &Apache::lonnet::critical(
1.740     www      5331:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5332:        &escape($message),$server);
1.662     raeburn  5333:     return $status;
                   5334: }
                   5335: 
1.658     raeburn  5336: sub dcmaildump {
                   5337:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5338:     my %returnhash=();
1.846     albertel 5339: 
                   5340:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5341:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5342:                                                          &escape($enddate).':';
                   5343: 	my @esc_senders=map { &escape($_)} @$senders;
                   5344: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5345: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5346:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5347:             if (($key) && ($value)) {
                   5348:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5349:             }
                   5350:         }
                   5351:     }
                   5352:     return %returnhash;
                   5353: }
1.662     raeburn  5354: # ---------------------------------------------------------- Domain roles
                   5355: 
                   5356: sub get_domain_roles {
                   5357:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5358:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5359:         $startdate = '.';
                   5360:     }
1.1018    raeburn  5361:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5362:         $enddate = '.';
                   5363:     }
1.922     raeburn  5364:     my $rolelist;
                   5365:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5366:         $rolelist = join('&',@{$roles});
1.922     raeburn  5367:     }
1.662     raeburn  5368:     my %personnel = ();
1.841     albertel 5369: 
                   5370:     my %servers = &get_servers($dom,'library');
                   5371:     foreach my $tryserver (keys(%servers)) {
                   5372: 	%{$personnel{$tryserver}}=();
                   5373: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5374: 					    &escape($startdate).':'.
                   5375: 					    &escape($enddate).':'.
                   5376: 					    &escape($rolelist), $tryserver))) {
                   5377: 	    my ($key,$value) = split(/\=/,$line,2);
                   5378: 	    if (($key) && ($value)) {
                   5379: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5380: 	    }
                   5381: 	}
1.662     raeburn  5382:     }
                   5383:     return %personnel;
                   5384: }
1.658     raeburn  5385: 
1.1172.2.89  raeburn  5386: sub get_active_domroles {
                   5387:     my ($dom,$roles) = @_;
                   5388:     return () unless (ref($roles) eq 'ARRAY');
                   5389:     my $now = time;
                   5390:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5391:     my %domroles;
                   5392:     foreach my $server (keys(%dompersonnel)) {
                   5393:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5394:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5395:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5396:         }
                   5397:     }
                   5398:     return %domroles;
                   5399: }
                   5400: 
1.1057    www      5401: # ----------------------------------------------------------- Interval timing 
1.149     www      5402: 
1.1153    www      5403: {
                   5404: # Caches needed for speedup of navmaps
                   5405: # We don't want to cache this for very long at all (5 seconds at most)
                   5406: # 
                   5407: # The user for whom we cache
                   5408: my $cachedkey='';
                   5409: # The cached times for this user
                   5410: my %cachedtimes=();
                   5411: # When this was last done
1.1172.2.66  raeburn  5412: my $cachedtime='';
1.1153    www      5413: 
                   5414: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5415:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5416:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5417:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5418:20):         (!$ignorecache)) {
1.1154    raeburn  5419:         return;
                   5420:     }
                   5421:     $cachedtime=time;
                   5422:     $cachedkey=$uname.':'.$udom;
                   5423:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5424: }
                   5425: 
1.504     albertel 5426: sub get_first_access {
1.1172.2.118.  .1(raebu 5427:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5428:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5429:     if ($argsymb) { $symb=$argsymb; }
                   5430:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5431:     if ($argmap) { $map = $argmap; }
1.926     albertel 5432:     if ($type eq 'course') {
                   5433: 	$res='course';
                   5434:     } elsif ($type eq 'map') {
1.588     albertel 5435: 	$res=&symbread($map);
                   5436:     } else {
                   5437: 	$res=$symb;
                   5438:     }
1.1172.2.118.  .1(raebu 5439:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5440:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5441: }
                   5442: 
                   5443: sub set_first_access {
1.1162    raeburn  5444:     my ($type,$interval)=@_;
1.790     albertel 5445:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5446:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5447:     if ($type eq 'course') {
                   5448: 	$res='course';
                   5449:     } elsif ($type eq 'map') {
1.588     albertel 5450: 	$res=&symbread($map);
                   5451:     } else {
                   5452: 	$res=$symb;
                   5453:     }
1.1153    www      5454:     $cachedkey='';
1.1162    raeburn  5455:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5456:     if ($firstaccess) {
                   5457:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5458:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5459:                  "in $courseid");
                   5460:         return 'already_set';
                   5461:     } else {
1.1162    raeburn  5462:         my $start = time;
                   5463: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5464:                           $udom,$uname);
                   5465:         if ($putres eq 'ok') {
                   5466:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5467:                  $udom,$uname); 
                   5468:             &appenv(
                   5469:                      {
                   5470:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5471:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5472:                      }
                   5473:                   );
1.1172.2.97  raeburn  5474:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5475:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5476:             }
1.1172.2.102  raeburn  5477:         } elsif ($putres ne 'refused') {
                   5478:             &logthis("Result: $putres when attempting to set first access time ".
                   5479:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5480:         }
                   5481:         return $putres;
1.505     albertel 5482:     }
                   5483:     return 'already_set';
1.504     albertel 5484: }
1.1153    www      5485: }
1.1172.2.32  raeburn  5486: 
                   5487: sub checkout {
                   5488:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5489:     my $now=time;
                   5490:     my $lonhost=$perlvar{'lonHostID'};
                   5491:     my $infostr=&escape(
                   5492:                  'CHECKOUTTOKEN&'.
                   5493:                  $tuname.'&'.
                   5494:                  $tudom.'&'.
                   5495:                  $tcrsid.'&'.
                   5496:                  $symb.'&'.
                   5497:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5498:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5499:     if ($token=~/^error\:/) {
                   5500:         &logthis("<font color=\"blue\">WARNING: ".
                   5501:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5502:                  "</font>");
                   5503:         return '';
                   5504:     }
                   5505: 
                   5506:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5507:     $token=~tr/a-z/A-Z/;
                   5508: 
                   5509:     my %infohash=('resource.0.outtoken' => $token,
                   5510:                   'resource.0.checkouttime' => $now,
                   5511:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5512: 
                   5513:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5514:        return '';
                   5515:     } else {
                   5516:         &logthis("<font color=\"blue\">WARNING: ".
                   5517:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5518:                  "</font>");
                   5519:     }
                   5520: 
                   5521:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5522:                          &escape('Checkout '.$infostr.' - '.
                   5523:                                                  $token)) ne 'ok') {
                   5524:         return '';
                   5525:     } else {
                   5526:         &logthis("<font color=\"blue\">WARNING: ".
                   5527:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5528:                  "</font>");
                   5529:     }
                   5530:     return $token;
                   5531: }
                   5532: 
                   5533: # ------------------------------------------------------------ Check in an item
                   5534: 
                   5535: sub checkin {
                   5536:     my $token=shift;
                   5537:     my $now=time;
                   5538:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5539:     $lonhost=~tr/A-Z/a-z/;
                   5540:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5541:     $dtoken=~s/\W/\_/g;
                   5542:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5543:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5544: 
                   5545:     unless (($tuname) && ($tudom)) {
                   5546:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5547:         return '';
                   5548:     }
                   5549: 
                   5550:     unless (&allowed('mgr',$tcrsid)) {
                   5551:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5552:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5553:         return '';
                   5554:     }
                   5555: 
                   5556:     my %infohash=('resource.0.intoken' => $token,
                   5557:                   'resource.0.checkintime' => $now,
                   5558:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5559: 
                   5560:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5561:        return '';
                   5562:     }
                   5563: 
                   5564:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5565:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5566:         return '';
                   5567:     }
                   5568: 
                   5569:     return ($symb,$tuname,$tudom,$tcrsid);
                   5570: }
                   5571: 
1.110     www      5572: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5573: 
                   5574: sub expirespread {
                   5575:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5576:     my $cid=$env{'request.course.id'}; 
1.110     www      5577:     if ($cid) {
                   5578:        my $now=time;
                   5579:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5580:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5581:                             $env{'course.'.$cid.'.num'}.
1.110     www      5582: 	        	    ':nohist_expirationdates:'.
                   5583:                             &escape($key).'='.$now,
1.620     albertel 5584:                             $env{'course.'.$cid.'.home'})
1.110     www      5585:     }
                   5586:     return 'ok';
1.14      www      5587: }
                   5588: 
1.109     www      5589: # ----------------------------------------------------- Devalidate Spreadsheets
                   5590: 
                   5591: sub devalidate {
1.325     www      5592:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5593:     my $cid=$env{'request.course.id'}; 
1.109     www      5594:     if ($cid) {
1.391     matthew  5595:         # delete the stored spreadsheets for
                   5596:         # - the student level sheet of this user in course's homespace
                   5597:         # - the assessment level sheet for this resource 
                   5598:         #   for this user in user's homespace
1.553     albertel 5599: 	# - current conditional state info
1.325     www      5600: 	my $key=$uname.':'.$udom.':';
1.109     www      5601:         my $status=
1.299     matthew  5602: 	    &del('nohist_calculatedsheets',
1.391     matthew  5603: 		 [$key.'studentcalc:'],
1.620     albertel 5604: 		 $env{'course.'.$cid.'.domain'},
                   5605: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5606: 		.' '.
                   5607: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5608: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5609:         unless ($status eq 'ok ok') {
                   5610:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5611:                     $uname.' at '.$udom.' for '.
1.109     www      5612: 		    $symb.': '.$status);
1.133     albertel 5613:         }
1.553     albertel 5614: 	&delenv('user.state.'.$cid);
1.109     www      5615:     }
                   5616: }
                   5617: 
1.265     albertel 5618: sub get_scalar {
                   5619:     my ($string,$end) = @_;
                   5620:     my $value;
                   5621:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5622: 	$value = $1;
                   5623:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5624: 	$value = $1;
                   5625:     }
                   5626:     return &unescape($value);
                   5627: }
                   5628: 
                   5629: sub array2str {
                   5630:   my (@array) = @_;
                   5631:   my $result=&arrayref2str(\@array);
                   5632:   $result=~s/^__ARRAY_REF__//;
                   5633:   $result=~s/__END_ARRAY_REF__$//;
                   5634:   return $result;
                   5635: }
                   5636: 
1.204     albertel 5637: sub arrayref2str {
                   5638:   my ($arrayref) = @_;
1.265     albertel 5639:   my $result='__ARRAY_REF__';
1.204     albertel 5640:   foreach my $elem (@$arrayref) {
1.265     albertel 5641:     if(ref($elem) eq 'ARRAY') {
                   5642:       $result.=&arrayref2str($elem).'&';
                   5643:     } elsif(ref($elem) eq 'HASH') {
                   5644:       $result.=&hashref2str($elem).'&';
                   5645:     } elsif(ref($elem)) {
                   5646:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5647:     } else {
                   5648:       $result.=&escape($elem).'&';
                   5649:     }
                   5650:   }
                   5651:   $result=~s/\&$//;
1.265     albertel 5652:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5653:   return $result;
                   5654: }
                   5655: 
1.168     albertel 5656: sub hash2str {
1.204     albertel 5657:   my (%hash) = @_;
                   5658:   my $result=&hashref2str(\%hash);
1.265     albertel 5659:   $result=~s/^__HASH_REF__//;
                   5660:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5661:   return $result;
                   5662: }
                   5663: 
                   5664: sub hashref2str {
                   5665:   my ($hashref)=@_;
1.265     albertel 5666:   my $result='__HASH_REF__';
1.800     albertel 5667:   foreach my $key (sort(keys(%$hashref))) {
                   5668:     if (ref($key) eq 'ARRAY') {
                   5669:       $result.=&arrayref2str($key).'=';
                   5670:     } elsif (ref($key) eq 'HASH') {
                   5671:       $result.=&hashref2str($key).'=';
                   5672:     } elsif (ref($key)) {
1.265     albertel 5673:       $result.='=';
1.800     albertel 5674:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5675:     } else {
1.1132    raeburn  5676: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5677:     }
                   5678: 
1.800     albertel 5679:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5680:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5681:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5682:       $result.=&hashref2str($hashref->{$key}).'&';
                   5683:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5684:        $result.='&';
1.800     albertel 5685:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5686:     } else {
1.800     albertel 5687:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5688:     }
                   5689:   }
1.168     albertel 5690:   $result=~s/\&$//;
1.265     albertel 5691:   $result .= '__END_HASH_REF__';
1.168     albertel 5692:   return $result;
                   5693: }
                   5694: 
                   5695: sub str2hash {
1.265     albertel 5696:     my ($string)=@_;
                   5697:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5698:     return %$hash;
                   5699: }
                   5700: 
                   5701: sub str2hashref {
1.168     albertel 5702:   my ($string) = @_;
1.265     albertel 5703: 
                   5704:   my %hash;
                   5705: 
                   5706:   if($string !~ /^__HASH_REF__/) {
                   5707:       if (! ($string eq '' || !defined($string))) {
                   5708: 	  $hash{'error'}='Not hash reference';
                   5709:       }
                   5710:       return (\%hash, $string);
                   5711:   }
                   5712: 
                   5713:   $string =~ s/^__HASH_REF__//;
                   5714: 
                   5715:   while($string !~ /^__END_HASH_REF__/) {
                   5716:       #key
                   5717:       my $key='';
                   5718:       if($string =~ /^__HASH_REF__/) {
                   5719:           ($key, $string)=&str2hashref($string);
                   5720:           if(defined($key->{'error'})) {
                   5721:               $hash{'error'}='Bad data';
                   5722:               return (\%hash, $string);
                   5723:           }
                   5724:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5725:           ($key, $string)=&str2arrayref($string);
                   5726:           if($key->[0] eq 'Array reference error') {
                   5727:               $hash{'error'}='Bad data';
                   5728:               return (\%hash, $string);
                   5729:           }
                   5730:       } else {
                   5731:           $string =~ s/^(.*?)=//;
1.267     albertel 5732: 	  $key=&unescape($1);
1.265     albertel 5733:       }
                   5734:       $string =~ s/^=//;
                   5735: 
                   5736:       #value
                   5737:       my $value='';
                   5738:       if($string =~ /^__HASH_REF__/) {
                   5739:           ($value, $string)=&str2hashref($string);
                   5740:           if(defined($value->{'error'})) {
                   5741:               $hash{'error'}='Bad data';
                   5742:               return (\%hash, $string);
                   5743:           }
                   5744:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5745:           ($value, $string)=&str2arrayref($string);
                   5746:           if($value->[0] eq 'Array reference error') {
                   5747:               $hash{'error'}='Bad data';
                   5748:               return (\%hash, $string);
                   5749:           }
                   5750:       } else {
                   5751: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5752:       }
                   5753:       $string =~ s/^&//;
                   5754: 
                   5755:       $hash{$key}=$value;
1.204     albertel 5756:   }
1.265     albertel 5757: 
                   5758:   $string =~ s/^__END_HASH_REF__//;
                   5759: 
                   5760:   return (\%hash, $string);
1.204     albertel 5761: }
                   5762: 
                   5763: sub str2array {
1.265     albertel 5764:     my ($string)=@_;
                   5765:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5766:     return @$array;
                   5767: }
                   5768: 
                   5769: sub str2arrayref {
1.204     albertel 5770:   my ($string) = @_;
1.265     albertel 5771:   my @array;
                   5772: 
                   5773:   if($string !~ /^__ARRAY_REF__/) {
                   5774:       if (! ($string eq '' || !defined($string))) {
                   5775: 	  $array[0]='Array reference error';
                   5776:       }
                   5777:       return (\@array, $string);
                   5778:   }
                   5779: 
                   5780:   $string =~ s/^__ARRAY_REF__//;
                   5781: 
                   5782:   while($string !~ /^__END_ARRAY_REF__/) {
                   5783:       my $value='';
                   5784:       if($string =~ /^__HASH_REF__/) {
                   5785:           ($value, $string)=&str2hashref($string);
                   5786:           if(defined($value->{'error'})) {
                   5787:               $array[0] ='Array reference error';
                   5788:               return (\@array, $string);
                   5789:           }
                   5790:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5791:           ($value, $string)=&str2arrayref($string);
                   5792:           if($value->[0] eq 'Array reference error') {
                   5793:               $array[0] ='Array reference error';
                   5794:               return (\@array, $string);
                   5795:           }
                   5796:       } else {
                   5797: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5798:       }
                   5799:       $string =~ s/^&//;
                   5800: 
                   5801:       push(@array, $value);
1.191     harris41 5802:   }
1.265     albertel 5803: 
                   5804:   $string =~ s/^__END_ARRAY_REF__//;
                   5805: 
                   5806:   return (\@array, $string);
1.168     albertel 5807: }
                   5808: 
1.167     albertel 5809: # -------------------------------------------------------------------Temp Store
                   5810: 
1.168     albertel 5811: sub tmpreset {
                   5812:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5813:   if (!$symb) {
                   5814:     $symb=&symbread();
1.620     albertel 5815:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5816:   }
                   5817:   $symb=escape($symb);
                   5818: 
1.620     albertel 5819:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5820:   $namespace=~s/\//\_/g;
                   5821:   $namespace=~s/\W//g;
                   5822: 
1.620     albertel 5823:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5824:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5825:   if ($domain eq 'public' && $stuname eq 'public') {
                   5826:       $stuname=$ENV{'REMOTE_ADDR'};
                   5827:   }
1.1117    foxr     5828:   my $path=LONCAPA::tempdir();
1.168     albertel 5829:   my %hash;
                   5830:   if (tie(%hash,'GDBM_File',
                   5831: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5832: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5833:     foreach my $key (keys(%hash)) {
1.180     albertel 5834:       if ($key=~ /:$symb/) {
1.168     albertel 5835: 	delete($hash{$key});
                   5836:       }
                   5837:     }
                   5838:   }
                   5839: }
                   5840: 
1.167     albertel 5841: sub tmpstore {
1.168     albertel 5842:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5843: 
                   5844:   if (!$symb) {
                   5845:     $symb=&symbread();
1.620     albertel 5846:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5847:   }
                   5848:   $symb=escape($symb);
                   5849: 
                   5850:   if (!$namespace) {
                   5851:     # I don't think we would ever want to store this for a course.
                   5852:     # it seems this will only be used if we don't have a course.
1.620     albertel 5853:     #$namespace=$env{'request.course.id'};
1.168     albertel 5854:     #if (!$namespace) {
1.620     albertel 5855:       $namespace=$env{'request.state'};
1.168     albertel 5856:     #}
                   5857:   }
                   5858:   $namespace=~s/\//\_/g;
                   5859:   $namespace=~s/\W//g;
1.620     albertel 5860:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5861:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5862:   if ($domain eq 'public' && $stuname eq 'public') {
                   5863:       $stuname=$ENV{'REMOTE_ADDR'};
                   5864:   }
1.168     albertel 5865:   my $now=time;
                   5866:   my %hash;
1.1117    foxr     5867:   my $path=LONCAPA::tempdir();
1.168     albertel 5868:   if (tie(%hash,'GDBM_File',
                   5869: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5870: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5871:     $hash{"version:$symb"}++;
                   5872:     my $version=$hash{"version:$symb"};
                   5873:     my $allkeys=''; 
                   5874:     foreach my $key (keys(%$storehash)) {
                   5875:       $allkeys.=$key.':';
1.591     albertel 5876:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5877:     }
                   5878:     $hash{"$version:$symb:timestamp"}=$now;
                   5879:     $allkeys.='timestamp';
                   5880:     $hash{"$version:keys:$symb"}=$allkeys;
                   5881:     if (untie(%hash)) {
                   5882:       return 'ok';
                   5883:     } else {
                   5884:       return "error:$!";
                   5885:     }
                   5886:   } else {
                   5887:     return "error:$!";
                   5888:   }
                   5889: }
1.167     albertel 5890: 
1.168     albertel 5891: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5892: 
1.168     albertel 5893: sub tmprestore {
                   5894:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5895: 
1.168     albertel 5896:   if (!$symb) {
                   5897:     $symb=&symbread();
1.620     albertel 5898:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5899:   }
                   5900:   $symb=escape($symb);
                   5901: 
1.620     albertel 5902:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5903: 
1.620     albertel 5904:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5905:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5906:   if ($domain eq 'public' && $stuname eq 'public') {
                   5907:       $stuname=$ENV{'REMOTE_ADDR'};
                   5908:   }
1.168     albertel 5909:   my %returnhash;
                   5910:   $namespace=~s/\//\_/g;
                   5911:   $namespace=~s/\W//g;
                   5912:   my %hash;
1.1117    foxr     5913:   my $path=LONCAPA::tempdir();
1.168     albertel 5914:   if (tie(%hash,'GDBM_File',
                   5915: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5916: 	  &GDBM_READER(),0640)) {
1.168     albertel 5917:     my $version=$hash{"version:$symb"};
                   5918:     $returnhash{'version'}=$version;
                   5919:     my $scope;
                   5920:     for ($scope=1;$scope<=$version;$scope++) {
                   5921:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5922:       my @keys=split(/:/,$vkeys);
                   5923:       my $key;
                   5924:       $returnhash{"$scope:keys"}=$vkeys;
                   5925:       foreach $key (@keys) {
1.591     albertel 5926: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5927: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5928:       }
                   5929:     }
1.168     albertel 5930:     if (!(untie(%hash))) {
                   5931:       return "error:$!";
                   5932:     }
                   5933:   } else {
                   5934:     return "error:$!";
                   5935:   }
                   5936:   return %returnhash;
1.167     albertel 5937: }
                   5938: 
1.9       www      5939: # ----------------------------------------------------------------------- Store
                   5940: 
                   5941: sub store {
1.1172.2.64  raeburn  5942:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5943:     my $home='';
                   5944: 
1.168     albertel 5945:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5946: 
1.213     www      5947:     $symb=&symbclean($symb);
1.122     albertel 5948:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5949: 
1.620     albertel 5950:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5951:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5952: 
                   5953:     &devalidate($symb,$stuname,$domain);
1.109     www      5954: 
                   5955:     $symb=escape($symb);
1.187     www      5956:     if (!$namespace) { 
1.620     albertel 5957:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5958:           return ''; 
                   5959:        } 
                   5960:     }
1.620     albertel 5961:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5962: 
                   5963:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5964:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5965: 
1.12      www      5966:     my $namevalue='';
1.800     albertel 5967:     foreach my $key (keys(%$storehash)) {
                   5968:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5969:     }
1.12      www      5970:     $namevalue=~s/\&$//;
1.187     www      5971:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5972:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5973: }
                   5974: 
1.47      www      5975: # -------------------------------------------------------------- Critical Store
                   5976: 
                   5977: sub cstore {
1.1172.2.64  raeburn  5978:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5979:     my $home='';
                   5980: 
1.168     albertel 5981:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5982: 
1.213     www      5983:     $symb=&symbclean($symb);
1.122     albertel 5984:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5985: 
1.620     albertel 5986:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5987:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5988: 
                   5989:     &devalidate($symb,$stuname,$domain);
1.109     www      5990: 
                   5991:     $symb=escape($symb);
1.187     www      5992:     if (!$namespace) { 
1.620     albertel 5993:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5994:           return ''; 
                   5995:        } 
                   5996:     }
1.620     albertel 5997:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5998: 
                   5999:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6000:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6001: 
1.47      www      6002:     my $namevalue='';
1.800     albertel 6003:     foreach my $key (keys(%$storehash)) {
                   6004:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6005:     }
1.47      www      6006:     $namevalue=~s/\&$//;
1.187     www      6007:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6008:     return critical
1.1172.2.64  raeburn  6009:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6010: }
                   6011: 
1.9       www      6012: # --------------------------------------------------------------------- Restore
                   6013: 
                   6014: sub restore {
1.124     www      6015:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6016:     my $home='';
                   6017: 
1.168     albertel 6018:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6019: 
1.122     albertel 6020:     if (!$symb) {
1.1172.2.26  raeburn  6021:         return if ($namespace eq 'courserequests');
                   6022:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6023:     } else {
1.1172.2.26  raeburn  6024:         unless ($namespace eq 'courserequests') {
                   6025:             $symb=&escape(&symbclean($symb));
                   6026:         }
1.122     albertel 6027:     }
1.188     www      6028:     if (!$namespace) { 
1.620     albertel 6029:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6030:           return ''; 
                   6031:        } 
                   6032:     }
1.620     albertel 6033:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6034:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6035:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6036:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6037: 
1.12      www      6038:     my %returnhash=();
1.800     albertel 6039:     foreach my $line (split(/\&/,$answer)) {
                   6040: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6041:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6042:     }
1.75      www      6043:     my $version;
                   6044:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6045:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6046:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6047:        }
1.75      www      6048:     }
1.13      www      6049:     return %returnhash;
1.34      www      6050: }
                   6051: 
                   6052: # ---------------------------------------------------------- Course Description
1.1118    foxr     6053: #
                   6054: #  
1.34      www      6055: 
                   6056: sub coursedescription {
1.731     albertel 6057:     my ($courseid,$args)=@_;
1.34      www      6058:     $courseid=~s/^\///;
1.49      www      6059:     $courseid=~s/\_/\//g;
1.34      www      6060:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6061:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6062:     my $normalid=$cdomain.'_'.$cnum;
                   6063:     # need to always cache even if we get errors otherwise we keep 
                   6064:     # trying and trying and trying to get the course description.
                   6065:     my %envhash=();
                   6066:     my %returnhash=();
1.731     albertel 6067:     
                   6068:     my $expiretime=600;
                   6069:     if ($env{'request.course.id'} eq $normalid) {
                   6070: 	$expiretime=120;
                   6071:     }
                   6072: 
                   6073:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6074:     if (!$args->{'freshen_cache'}
                   6075: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6076: 	foreach my $key (keys(%env)) {
                   6077: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6078: 	    my ($setting) = $1;
                   6079: 	    $returnhash{$setting} = $env{$key};
                   6080: 	}
                   6081: 	return %returnhash;
                   6082:     }
                   6083: 
1.1118    foxr     6084:     # get the data again
                   6085: 
1.731     albertel 6086:     if (!$args->{'one_time'}) {
                   6087: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6088:     }
1.811     albertel 6089: 
1.34      www      6090:     if ($chome ne 'no_host') {
1.302     albertel 6091:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6092:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6093: 	   my $username = $env{'user.name'}; # Defult username
                   6094: 	   if(defined $args->{'user'}) {
                   6095: 	       $username = $args->{'user'};
                   6096: 	   }
1.129     albertel 6097:            $returnhash{'home'}= $chome;
                   6098: 	   $returnhash{'domain'} = $cdomain;
                   6099: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6100:            if (!defined($returnhash{'type'})) {
                   6101:                $returnhash{'type'} = 'Course';
                   6102:            }
1.130     albertel 6103:            while (my ($name,$value) = each %returnhash) {
1.53      www      6104:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6105:            }
1.270     www      6106:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6107:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6108: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6109:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6110:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6111:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6112:        }
                   6113:     }
1.731     albertel 6114:     if (!$args->{'one_time'}) {
1.949     raeburn  6115: 	&appenv(\%envhash);
1.731     albertel 6116:     }
1.302     albertel 6117:     return %returnhash;
1.461     www      6118: }
                   6119: 
1.1080    raeburn  6120: sub update_released_required {
                   6121:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6122:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6123:         $cid = $env{'request.course.id'};
                   6124:         $cdom = $env{'course.'.$cid.'.domain'};
                   6125:         $cnum = $env{'course.'.$cid.'.num'};
                   6126:         $chome = $env{'course.'.$cid.'.home'};
                   6127:     }
                   6128:     if ($needsrelease) {
                   6129:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6130:         my $needsupdate;
                   6131:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6132:             $needsupdate = 1;
                   6133:         } else {
                   6134:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6135:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6136:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6137:                 $needsupdate = 1;
                   6138:             }
                   6139:         }
                   6140:         if ($needsupdate) {
                   6141:             my %needshash = (
                   6142:                              'internal.releaserequired' => $needsrelease,
                   6143:                             );
                   6144:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6145:             if ($putresult eq 'ok') {
                   6146:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6147:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6148:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6149:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6150:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6151:                 }
                   6152:             }
                   6153:         }
                   6154:     }
                   6155:     return;
                   6156: }
                   6157: 
1.461     www      6158: # -------------------------------------------------See if a user is privileged
                   6159: 
                   6160: sub privileged {
1.1172.2.23  raeburn  6161:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6162:     my $now = time;
1.1172.2.23  raeburn  6163:     my $roles;
                   6164:     if (ref($possroles) eq 'ARRAY') {
                   6165:         $roles = $possroles;
                   6166:     } else {
                   6167:         $roles = ['dc','su'];
                   6168:     }
                   6169:     if (ref($possdomains) eq 'ARRAY') {
                   6170:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6171:         foreach my $dom (@{$possdomains}) {
                   6172:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6173:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6174:                 foreach my $role (@{$roles}) {
                   6175:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6176:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6177:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6178:                             return 1 unless (($end && $end < $now) ||
                   6179:                                              ($start && $start > $now));
                   6180:                         }
                   6181:                     }
                   6182:                 }
                   6183:             }
                   6184:         }
                   6185:     } else {
                   6186:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6187:         my $now = time;
1.1170    droeschl 6188: 
1.1172.2.58  raeburn  6189:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6190:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6191:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6192:                 return 1 unless ($tend && $tend < $now)
                   6193:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6194:             }
1.1172.2.23  raeburn  6195:         }
                   6196:     }
1.461     www      6197:     return 0;
1.9       www      6198: }
1.1       albertel 6199: 
1.1172.2.23  raeburn  6200: sub privileged_by_domain {
                   6201:     my ($domains,$roles) = @_;
                   6202:     my %privileged = ();
                   6203:     my $cachetime = 60*60*24;
                   6204:     my $now = time;
                   6205:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6206:         return %privileged;
                   6207:     }
                   6208:     foreach my $dom (@{$domains}) {
                   6209:         next if (ref($privileged{$dom}) eq 'HASH');
                   6210:         my $needroles;
                   6211:         foreach my $role (@{$roles}) {
                   6212:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6213:             if (defined($cached)) {
                   6214:                 if (ref($result) eq 'HASH') {
                   6215:                     $privileged{$dom}{$role} = $result;
                   6216:                 }
                   6217:             } else {
                   6218:                 $needroles = 1;
                   6219:             }
                   6220:         }
                   6221:         if ($needroles) {
                   6222:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6223:             $privileged{$dom} = {};
                   6224:             foreach my $server (keys(%dompersonnel)) {
                   6225:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6226:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6227:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6228:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6229:                         next if ($end && $end < $now);
                   6230:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6231:                             $dompersonnel{$server}{$item};
                   6232:                     }
                   6233:                 }
                   6234:             }
                   6235:             if (ref($privileged{$dom}) eq 'HASH') {
                   6236:                 foreach my $role (@{$roles}) {
                   6237:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6238:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6239:                     } else {
                   6240:                         my %hash = ();
                   6241:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6242:                     }
                   6243:                 }
                   6244:             }
                   6245:         }
                   6246:     }
                   6247:     return %privileged;
                   6248: }
                   6249: 
1.103     harris41 6250: # -------------------------------------------------------- Get user privileges
1.11      www      6251: 
                   6252: sub rolesinit {
1.1169    droeschl 6253:     my ($domain, $username) = @_;
                   6254:     my %userroles = ('user.login.time' => time);
                   6255:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6256: 
                   6257:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6258:     # also, blocking can be triggered by an activating timer
                   6259:     # it's saved in the user's %env.
                   6260:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6261:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6262:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6263:         %timerintchk, %timerintenv);
                   6264: 
1.1162    raeburn  6265:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6266:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6267:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6268:     }
1.1169    droeschl 6269: 
1.1162    raeburn  6270:     foreach my $key (keys(%timerinterval)) {
                   6271:         my ($cid,$rest) = split(/\0/,$key);
                   6272:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6273:     }
1.1169    droeschl 6274: 
1.11      www      6275:     my %allroles=();
1.1162    raeburn  6276:     my %allgroups=();
1.11      www      6277: 
1.1172.2.58  raeburn  6278:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6279:         my $role = $rolesdump{$area};
                   6280:         $area =~ s/\_\w\w$//;
                   6281: 
                   6282:         my ($trole, $tend, $tstart, $group_privs);
                   6283: 
                   6284:         if ($role =~ /^cr/) {
                   6285:         # Custom role, defined by a user 
                   6286:         # e.g., user.role.cr/msu/smith/mynewrole
                   6287:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6288:                 $trole = $1;
                   6289:                 ($tend, $tstart) = split('_', $2);
                   6290:             } else {
                   6291:                 $trole = $role;
                   6292:             }
                   6293:         } elsif ($role =~ m|^gr/|) {
                   6294:         # Role of member in a group, defined within a course/community
                   6295:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6296:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6297:             next if $tstart eq '-1';
                   6298:             ($trole, $group_privs) = split(/\//, $trole);
                   6299:             $group_privs = &unescape($group_privs);
                   6300:         } else {
                   6301:         # Just a normal role, defined in roles.tab
                   6302:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6303:         }
                   6304: 
                   6305:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6306:                  $username);
                   6307:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6308: 
                   6309:         # role expired or not available yet?
                   6310:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6311:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6312: 
                   6313:         next if $area eq '' or $trole eq '';
                   6314: 
                   6315:         my $spec = "$trole.$area";
                   6316:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6317: 
                   6318:         if ($trole =~ /^cr\//) {
                   6319:         # Custom role, defined by a user
                   6320:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6321:         } elsif ($trole eq 'gr') {
                   6322:         # Role of a member in a group, defined within a course/community
                   6323:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6324:             next;
                   6325:         } else {
                   6326:         # Normal role, defined in roles.tab
                   6327:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6328:         }
                   6329: 
                   6330:         my $cid = $tdomain.'_'.$trest;
                   6331:         unless ($firstaccchk{$cid}) {
                   6332:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6333:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6334:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6335:                         $coursetimerstarts{$cid}{$item}; 
                   6336:                 }
                   6337:             }
                   6338:             $firstaccchk{$cid} = 1;
                   6339:         }
                   6340:         unless ($timerintchk{$cid}) {
                   6341:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6342:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6343:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6344:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6345:                 }
1.12      www      6346:             }
1.1169    droeschl 6347:             $timerintchk{$cid} = 1;
1.191     harris41 6348:         }
1.11      www      6349:     }
1.1169    droeschl 6350: 
1.1172.2.91  raeburn  6351:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6352:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6353:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6354:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6355: 
1.1162    raeburn  6356:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6357: }
                   6358: 
1.567     raeburn  6359: sub set_arearole {
1.1172.2.19  raeburn  6360:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6361:     unless ($nolog) {
1.567     raeburn  6362: # log the associated role with the area
1.1172.2.19  raeburn  6363:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6364:     }
1.743     albertel 6365:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6366: }
                   6367: 
                   6368: sub custom_roleprivs {
                   6369:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6370:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6371:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6372:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6373:         my ($rdummy,$roledef)=
                   6374:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6375:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6376:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6377:             if (defined($syspriv)) {
1.1043    raeburn  6378:                 if ($trest =~ /^$match_community$/) {
                   6379:                     $syspriv =~ s/bre\&S//; 
                   6380:                 }
1.567     raeburn  6381:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6382:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6383:             }
                   6384:             if ($tdomain ne '') {
                   6385:                 if (defined($dompriv)) {
                   6386:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6387:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6388:                 }
                   6389:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6390:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6391:                         my $rolename = $1;
                   6392:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6393:                     }
1.567     raeburn  6394:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6395:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6396:                 }
                   6397:             }
                   6398:         }
                   6399:     }
                   6400: }
                   6401: 
1.1172.2.89  raeburn  6402: sub course_adhocrole_privs {
                   6403:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6404:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6405:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6406:         my (%currprivs,%storeprivs);
                   6407:         foreach my $item (split(/:/,$coursepriv)) {
                   6408:             my ($priv,$restrict) = split(/\&/,$item);
                   6409:             $currprivs{$priv} = $restrict;
                   6410:         }
                   6411:         my (%possadd,%possremove,%full);
                   6412:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6413:             my ($priv,$restrict)=split(/\&/,$item);
                   6414:             $full{$priv} = $restrict;
                   6415:         }
                   6416:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6417:              next if ($item eq '');
                   6418:              my ($rule,$rest) = split(/=/,$item);
                   6419:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6420:              foreach my $priv (split(/:/,$rest)) {
                   6421:                  if ($priv ne '') {
                   6422:                      if ($rule eq 'off') {
                   6423:                          $possremove{$priv} = 1;
                   6424:                      } else {
                   6425:                          $possadd{$priv} = 1;
                   6426:                      }
                   6427:                  }
                   6428:              }
                   6429:          }
                   6430:          foreach my $priv (sort(keys(%full))) {
                   6431:              if (exists($currprivs{$priv})) {
                   6432:                  unless (exists($possremove{$priv})) {
                   6433:                      $storeprivs{$priv} = $currprivs{$priv};
                   6434:                  }
                   6435:              } elsif (exists($possadd{$priv})) {
                   6436:                  $storeprivs{$priv} = $full{$priv};
                   6437:              }
                   6438:          }
                   6439:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6440:      }
                   6441:      return $coursepriv;
                   6442: }
                   6443: 
1.678     raeburn  6444: sub group_roleprivs {
                   6445:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6446:     my $access = 1;
                   6447:     my $now = time;
                   6448:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6449:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6450:     if ($access) {
1.811     albertel 6451:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6452:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6453:     }
                   6454: }
1.567     raeburn  6455: 
                   6456: sub standard_roleprivs {
                   6457:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6458:     if (defined($pr{$trole.':s'})) {
                   6459:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6460:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6461:     }
                   6462:     if ($tdomain ne '') {
                   6463:         if (defined($pr{$trole.':d'})) {
                   6464:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6465:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6466:         }
                   6467:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6468:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6469:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6470:         }
                   6471:     }
                   6472: }
                   6473: 
                   6474: sub set_userprivs {
1.1064    raeburn  6475:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6476:     my $author=0;
                   6477:     my $adv=0;
1.1172.2.91  raeburn  6478:     my $rar=0;
1.678     raeburn  6479:     my %grouproles = ();
                   6480:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6481:         my @groupkeys; 
1.1000    raeburn  6482:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6483:             push(@groupkeys,$role);
                   6484:         }
                   6485:         if (ref($groups_roles) eq 'HASH') {
                   6486:             foreach my $key (keys(%{$groups_roles})) {
                   6487:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6488:                     push(@groupkeys,$key);
                   6489:                 }
                   6490:             }
                   6491:         }
                   6492:         if (@groupkeys > 0) {
                   6493:             foreach my $role (@groupkeys) {
                   6494:                 my ($trole,$area,$sec,$extendedarea);
                   6495:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6496:                     $trole = $1;
                   6497:                     $area = $2;
                   6498:                     $sec = $3;
                   6499:                     $extendedarea = $area.$sec;
                   6500:                     if (exists($$allgroups{$area})) {
                   6501:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6502:                             my $spec = $trole.'.'.$extendedarea;
                   6503:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6504:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6505:                         }
1.678     raeburn  6506:                     }
                   6507:                 }
                   6508:             }
                   6509:         }
                   6510:     }
1.800     albertel 6511:     foreach my $group (keys(%grouproles)) {
                   6512:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6513:     }
1.800     albertel 6514:     foreach my $role (keys(%{$allroles})) {
                   6515:         my %thesepriv;
1.941     raeburn  6516:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6517:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6518:             if ($item ne '') {
                   6519:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6520:                 if ($restrictions eq '') {
                   6521:                     $thesepriv{$privilege}='F';
                   6522:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6523:                     $thesepriv{$privilege}.=$restrictions;
                   6524:                 }
                   6525:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6526:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6527:             }
                   6528:         }
                   6529:         my $thesestr='';
1.1104    raeburn  6530:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6531: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6532: 	}
                   6533:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6534:     }
1.1172.2.91  raeburn  6535:     return ($author,$adv,$rar);
1.567     raeburn  6536: }
                   6537: 
1.994     raeburn  6538: sub role_status {
1.1104    raeburn  6539:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6540:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6541:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6542:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6543:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6544:             $$where = '/'.$two;
1.994     raeburn  6545:             $$trolecode=$$role.'.'.$$where;
                   6546:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6547:             $$tstatus='is';
1.1104    raeburn  6548:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6549:                 $$tstatus='future';
1.1034    raeburn  6550:                 if ($$tstart<$now) {
                   6551:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6552:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6553:                             my (%allroles,%allgroups,$group_privs,
                   6554:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6555:                             my %userroles = (
                   6556:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6557:                             );
1.1064    raeburn  6558:                             @rolecodes = ('cm'); 
1.1002    raeburn  6559:                             my $spec=$$role.'.'.$$where;
                   6560:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6561:                             if ($$role =~ /^cr\//) {
                   6562:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6563:                                 push(@rolecodes,'cr');
1.1002    raeburn  6564:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6565:                                 push(@rolecodes,$$role);
1.1002    raeburn  6566:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6567:                                                     $env{'user.name'});
1.1064    raeburn  6568:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6569:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6570:                                 $group_privs = &unescape($group_privs);
                   6571:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6572:                                 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  6573:                                 &get_groups_roles($tdomain,$trest,
                   6574:                                                   \%course_roles,\@rolecodes,
                   6575:                                                   \%groups_roles);
1.1002    raeburn  6576:                             } else {
1.1064    raeburn  6577:                                 push(@rolecodes,$$role);
1.1002    raeburn  6578:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6579:                             }
1.1172.2.91  raeburn  6580:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6581:                                                                    \%groups_roles);
1.1064    raeburn  6582:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6583:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6584:                         }
                   6585:                     }
1.1034    raeburn  6586:                     $$tstatus = 'is';
1.1002    raeburn  6587:                 }
1.994     raeburn  6588:             }
                   6589:             if ($$tend) {
1.1104    raeburn  6590:                 if ($$tend<$update) {
1.994     raeburn  6591:                     $$tstatus='expired';
                   6592:                 } elsif ($$tend<$now) {
                   6593:                     $$tstatus='will_not';
                   6594:                 }
                   6595:             }
                   6596:         }
                   6597:     }
                   6598: }
                   6599: 
1.1104    raeburn  6600: sub get_groups_roles {
                   6601:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6602:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6603:                   (ref($rolecodes) eq 'ARRAY') && 
                   6604:                   (ref($groups_roles) eq 'HASH')); 
                   6605:     if (keys(%{$cdom_courseroles}) > 0) {
                   6606:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6607:         if ($cdom ne '' && $cnum ne '') {
                   6608:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6609:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6610:                     my $crsrole = $1;
                   6611:                     my $crssec = $2;
                   6612:                     if ($crsrole =~ /^cr/) {
                   6613:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6614:                             push(@{$rolecodes},'cr');
                   6615:                         }
                   6616:                     } else {
                   6617:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6618:                             push(@{$rolecodes},$crsrole);
                   6619:                         }
                   6620:                     }
                   6621:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6622:                     if ($crssec ne '') {
                   6623:                         $rolekey .= "/$crssec";
                   6624:                     }
                   6625:                     $rolekey .= './';
                   6626:                     $groups_roles->{$rolekey} = $rolecodes;
                   6627:                 }
                   6628:             }
                   6629:         }
                   6630:     }
                   6631:     return;
                   6632: }
                   6633: 
                   6634: sub delete_env_groupprivs {
                   6635:     my ($where,$courseroles,$possroles) = @_;
                   6636:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6637:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6638:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6639:         %{$courseroles->{$udom}} =
                   6640:             &get_my_roles('','','userroles',['active'],
                   6641:                           $possroles,[$udom],1);
                   6642:     }
                   6643:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6644:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6645:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6646:             my $area = '/'.$cdom.'/'.$cnum;
                   6647:             my $privkey = "user.priv.$crsrole.$area";
                   6648:             if ($crssec ne '') {
                   6649:                 $privkey .= '/'.$crssec;
                   6650:             }
                   6651:             $privkey .= ".$area/$group";
                   6652:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6653:         }
                   6654:     }
                   6655:     return;
                   6656: }
                   6657: 
1.994     raeburn  6658: sub check_adhoc_privs {
1.1172.2.86  raeburn  6659:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6660:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6661:     if ($sec) {
                   6662:         $cckey .= '/'.$sec;
                   6663:     }
1.1172.2.9  raeburn  6664:     my $setprivs;
1.994     raeburn  6665:     if ($env{$cckey}) {
                   6666:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6667:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6668:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6669:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6670:             $setprivs = 1;
1.994     raeburn  6671:         }
                   6672:     } else {
1.1172.2.87  raeburn  6673:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6674:         $setprivs = 1;
1.994     raeburn  6675:     }
1.1172.2.9  raeburn  6676:     return $setprivs;
1.994     raeburn  6677: }
                   6678: 
                   6679: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6680: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6681:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6682:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6683:     if ($sec ne '') {
                   6684:         $area .= '/'.$sec;
                   6685:     }
1.994     raeburn  6686:     my $spec = $role.'.'.$area;
                   6687:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6688:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6689:     my %rolehash = ();
1.1172.2.89  raeburn  6690:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6691:         my $rolename = $1;
1.1172.2.84  raeburn  6692:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6693:         my %domdef = &get_domain_defaults($dcdom);
                   6694:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6695:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6696:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6697:             }
                   6698:         }
1.1172.2.84  raeburn  6699:     } else {
                   6700:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6701:     }
1.1172.2.91  raeburn  6702:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6703:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6704:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6705:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6706:         &appenv( {'request.role'        => $spec,
                   6707:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6708:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6709:                  }
                   6710:                );
                   6711:         my $tadv=0;
                   6712:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6713:         &appenv({'request.role.adv'    => $tadv});
                   6714:     }
1.994     raeburn  6715: }
                   6716: 
1.12      www      6717: # --------------------------------------------------------------- get interface
                   6718: 
                   6719: sub get {
1.131     albertel 6720:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6721:    my $items='';
1.800     albertel 6722:    foreach my $item (@$storearr) {
                   6723:        $items.=&escape($item).'&';
1.191     harris41 6724:    }
1.12      www      6725:    $items=~s/\&$//;
1.620     albertel 6726:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6727:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6728:    my $uhome=&homeserver($uname,$udomain);
                   6729: 
1.133     albertel 6730:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6731:    my @pairs=split(/\&/,$rep);
1.273     albertel 6732:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6733:      return @pairs;
                   6734:    }
1.15      www      6735:    my %returnhash=();
1.42      www      6736:    my $i=0;
1.800     albertel 6737:    foreach my $item (@$storearr) {
                   6738:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6739:       $i++;
1.191     harris41 6740:    }
1.15      www      6741:    return %returnhash;
1.27      www      6742: }
                   6743: 
                   6744: # --------------------------------------------------------------- del interface
                   6745: 
                   6746: sub del {
1.133     albertel 6747:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6748:    my $items='';
1.800     albertel 6749:    foreach my $item (@$storearr) {
                   6750:        $items.=&escape($item).'&';
1.191     harris41 6751:    }
1.984     neumanie 6752: 
1.27      www      6753:    $items=~s/\&$//;
1.620     albertel 6754:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6755:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6756:    my $uhome=&homeserver($uname,$udomain);
                   6757:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6758: }
                   6759: 
                   6760: # -------------------------------------------------------------- dump interface
                   6761: 
1.1172.2.22  raeburn  6762: sub unserialize {
                   6763:     my ($rep, $escapedkeys) = @_;
                   6764: 
                   6765:     return {} if $rep =~ /^error/;
                   6766: 
                   6767:     my %returnhash=();
                   6768:     foreach my $item (split(/\&/,$rep)) {
                   6769:         my ($key, $value) = split(/=/, $item, 2);
                   6770:         $key = unescape($key) unless $escapedkeys;
                   6771:         next if $key =~ /^error: 2 /;
                   6772:         $returnhash{$key} = &thaw_unescape($value);
                   6773:     }
                   6774:     return \%returnhash;
                   6775: }
                   6776: 
                   6777: # see Lond::dump_with_regexp
                   6778: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6779: sub dump {
1.1172.2.22  raeburn  6780:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6781:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6782:     if (!$uname) { $uname=$env{'user.name'}; }
                   6783:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6784: 
1.1172.2.55  raeburn  6785:     if ($regexp) {
                   6786:         $regexp=&escape($regexp);
                   6787:     } else {
                   6788:         $regexp='.';
                   6789:     }
1.1172.2.22  raeburn  6790:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6791:         # user is hosted on this machine
1.1172.2.55  raeburn  6792:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6793:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6794:         return %{&unserialize($reply, $escapedkeys)};
                   6795:     }
1.1166    raeburn  6796:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6797:     my @pairs=split(/\&/,$rep);
                   6798:     my %returnhash=();
1.1098    foxr     6799:     if (!($rep =~ /^error/ )) {
                   6800: 	foreach my $item (@pairs) {
                   6801: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6802:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6803: 	    next if ($key =~ /^error: 2 /);
                   6804: 	    $returnhash{$key}=&thaw_unescape($value);
                   6805: 	}
1.755     albertel 6806:     }
                   6807:     return %returnhash;
1.407     www      6808: }
                   6809: 
1.1098    foxr     6810: 
1.717     albertel 6811: # --------------------------------------------------------- dumpstore interface
                   6812: 
                   6813: sub dumpstore {
                   6814:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6815:    # same as dump but keys must be escaped. They may contain colon separated
                   6816:    # lists of values that may themself contain colons (e.g. symbs).
                   6817:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6818: }
                   6819: 
1.407     www      6820: # -------------------------------------------------------------- keys interface
                   6821: 
                   6822: sub getkeys {
                   6823:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6824:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6825:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6826:    my $uhome=&homeserver($uname,$udomain);
                   6827:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6828:    my @keyarray=();
1.800     albertel 6829:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6830:       next if ($key =~ /^error: 2 /);
1.800     albertel 6831:       push(@keyarray,&unescape($key));
1.407     www      6832:    }
                   6833:    return @keyarray;
1.318     matthew  6834: }
                   6835: 
1.319     matthew  6836: # --------------------------------------------------------------- currentdump
                   6837: sub currentdump {
1.328     matthew  6838:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6839:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6840:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6841:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6842:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6843:    my $rep;
                   6844: 
                   6845:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6846:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6847:                    $courseid)));
                   6848:    } else {
                   6849:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6850:    }
                   6851: 
1.318     matthew  6852:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6853:    #
1.318     matthew  6854:    my %returnhash=();
1.319     matthew  6855:    #
1.1172.2.118.  .1(raebu 6856:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6857:        # an old lond will not know currentdump
                   6858:        # Do a dump and make it look like a currentdump
1.822     albertel 6859:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6860:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6861:        my %hash = @tmp;
                   6862:        @tmp=();
1.424     matthew  6863:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6864:    } else {
                   6865:        my @pairs=split(/\&/,$rep);
1.800     albertel 6866:        foreach my $pair (@pairs) {
                   6867:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6868:            my ($symb,$param) = split(/:/,$key);
                   6869:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6870:                                                         &thaw_unescape($value);
1.319     matthew  6871:        }
1.191     harris41 6872:    }
1.12      www      6873:    return %returnhash;
1.424     matthew  6874: }
                   6875: 
                   6876: sub convert_dump_to_currentdump{
                   6877:     my %hash = %{shift()};
                   6878:     my %returnhash;
                   6879:     # Code ripped from lond, essentially.  The only difference
                   6880:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6881:     # we might run in to problems with parameter names =~ /^v\./
                   6882:     while (my ($key,$value) = each(%hash)) {
                   6883:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6884: 	$symb  = &unescape($symb);
                   6885: 	$param = &unescape($param);
1.424     matthew  6886:         next if ($v eq 'version' || $symb eq 'keys');
                   6887:         next if (exists($returnhash{$symb}) &&
                   6888:                  exists($returnhash{$symb}->{$param}) &&
                   6889:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6890:         $returnhash{$symb}->{$param}=$value;
                   6891:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6892:     }
                   6893:     #
                   6894:     # Remove all of the keys in the hashes which keep track of
                   6895:     # the version of the parameter.
                   6896:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6897:         # use a foreach because we are going to delete from the hash.
                   6898:         foreach my $key (keys(%$param_hash)) {
                   6899:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6900:         }
                   6901:     }
                   6902:     return \%returnhash;
1.12      www      6903: }
                   6904: 
1.627     albertel 6905: # ------------------------------------------------------ critical inc interface
                   6906: 
                   6907: sub cinc {
                   6908:     return &inc(@_,'critical');
                   6909: }
                   6910: 
1.449     matthew  6911: # --------------------------------------------------------------- inc interface
                   6912: 
                   6913: sub inc {
1.627     albertel 6914:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6915:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6916:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6917:     my $uhome=&homeserver($uname,$udomain);
                   6918:     my $items='';
                   6919:     if (! ref($store)) {
                   6920:         # got a single value, so use that instead
                   6921:         $items = &escape($store).'=&';
                   6922:     } elsif (ref($store) eq 'SCALAR') {
                   6923:         $items = &escape($$store).'=&';        
                   6924:     } elsif (ref($store) eq 'ARRAY') {
                   6925:         $items = join('=&',map {&escape($_);} @{$store});
                   6926:     } elsif (ref($store) eq 'HASH') {
                   6927:         while (my($key,$value) = each(%{$store})) {
                   6928:             $items.= &escape($key).'='.&escape($value).'&';
                   6929:         }
                   6930:     }
                   6931:     $items=~s/\&$//;
1.627     albertel 6932:     if ($critical) {
                   6933: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6934:     } else {
                   6935: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6936:     }
1.449     matthew  6937: }
                   6938: 
1.12      www      6939: # --------------------------------------------------------------- put interface
                   6940: 
                   6941: sub put {
1.134     albertel 6942:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6943:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6944:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6945:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6946:    my $items='';
1.800     albertel 6947:    foreach my $item (keys(%$storehash)) {
                   6948:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6949:    }
1.12      www      6950:    $items=~s/\&$//;
1.134     albertel 6951:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6952: }
                   6953: 
1.631     albertel 6954: # ------------------------------------------------------------ newput interface
                   6955: 
                   6956: sub newput {
                   6957:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6958:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6959:    if (!$uname) { $uname=$env{'user.name'}; }
                   6960:    my $uhome=&homeserver($uname,$udomain);
                   6961:    my $items='';
                   6962:    foreach my $key (keys(%$storehash)) {
                   6963:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6964:    }
                   6965:    $items=~s/\&$//;
                   6966:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6967: }
                   6968: 
                   6969: # ---------------------------------------------------------  putstore interface
                   6970: 
1.524     raeburn  6971: sub putstore {
1.1172.2.59  raeburn  6972:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6973:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6974:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6975:    my $uhome=&homeserver($uname,$udomain);
                   6976:    my $items='';
1.715     albertel 6977:    foreach my $key (keys(%$storehash)) {
                   6978:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6979:    }
1.715     albertel 6980:    $items=~s/\&$//;
1.716     albertel 6981:    my $esc_symb=&escape($symb);
                   6982:    my $esc_v=&escape($version);
1.715     albertel 6983:    my $reply =
1.716     albertel 6984:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6985: 	      $uhome);
1.1172.2.59  raeburn  6986:    if (($tolog) && ($reply eq 'ok')) {
                   6987:        my $namevalue='';
                   6988:        foreach my $key (keys(%{$storehash})) {
                   6989:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6990:        }
                   6991:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6992:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6993:                      '&version='.$esc_v.
                   6994:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6995:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6996:    }
1.715     albertel 6997:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6998:        # gfall back to way things use to be done
1.715     albertel 6999:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7000: 			    $uname);
1.524     raeburn  7001:    }
1.715     albertel 7002:    return $reply;
                   7003: }
                   7004: 
                   7005: sub old_putstore {
1.716     albertel 7006:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7007:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7008:     if (!$uname) { $uname=$env{'user.name'}; }
                   7009:     my $uhome=&homeserver($uname,$udomain);
                   7010:     my %newstorehash;
1.800     albertel 7011:     foreach my $item (keys(%$storehash)) {
                   7012: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7013: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7014:     }
                   7015:     my $items='';
                   7016:     my %allitems = ();
1.800     albertel 7017:     foreach my $item (keys(%newstorehash)) {
                   7018: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7019: 	    my $key = $1.':keys:'.$2;
                   7020: 	    $allitems{$key} .= $3.':';
                   7021: 	}
1.800     albertel 7022: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7023:     }
1.800     albertel 7024:     foreach my $item (keys(%allitems)) {
                   7025: 	$allitems{$item} =~ s/\:$//;
                   7026: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7027:     }
                   7028:     $items=~s/\&$//;
                   7029:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7030: }
                   7031: 
1.47      www      7032: # ------------------------------------------------------ critical put interface
                   7033: 
                   7034: sub cput {
1.134     albertel 7035:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7036:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7037:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7038:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7039:    my $items='';
1.800     albertel 7040:    foreach my $item (keys(%$storehash)) {
                   7041:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7042:    }
1.47      www      7043:    $items=~s/\&$//;
1.134     albertel 7044:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7045: }
                   7046: 
                   7047: # -------------------------------------------------------------- eget interface
                   7048: 
                   7049: sub eget {
1.133     albertel 7050:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7051:    my $items='';
1.800     albertel 7052:    foreach my $item (@$storearr) {
                   7053:        $items.=&escape($item).'&';
1.191     harris41 7054:    }
1.12      www      7055:    $items=~s/\&$//;
1.620     albertel 7056:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7057:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7058:    my $uhome=&homeserver($uname,$udomain);
                   7059:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7060:    my @pairs=split(/\&/,$rep);
                   7061:    my %returnhash=();
1.42      www      7062:    my $i=0;
1.800     albertel 7063:    foreach my $item (@$storearr) {
                   7064:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7065:       $i++;
1.191     harris41 7066:    }
1.12      www      7067:    return %returnhash;
                   7068: }
                   7069: 
1.667     albertel 7070: # ------------------------------------------------------------ tmpput interface
                   7071: sub tmpput {
1.802     raeburn  7072:     my ($storehash,$server,$context)=@_;
1.667     albertel 7073:     my $items='';
1.800     albertel 7074:     foreach my $item (keys(%$storehash)) {
                   7075: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7076:     }
                   7077:     $items=~s/\&$//;
1.802     raeburn  7078:     if (defined($context)) {
                   7079:         $items .= ':'.&escape($context);
                   7080:     }
1.667     albertel 7081:     return &reply("tmpput:$items",$server);
                   7082: }
                   7083: 
                   7084: # ------------------------------------------------------------ tmpget interface
                   7085: sub tmpget {
1.688     albertel 7086:     my ($token,$server)=@_;
                   7087:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7088:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7089:     my %returnhash;
1.1172.2.85  raeburn  7090:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7091:         return %returnhash;
                   7092:     }
1.667     albertel 7093:     foreach my $item (split(/\&/,$rep)) {
                   7094: 	my ($key,$value)=split(/=/,$item);
                   7095: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7096:     }
                   7097:     return %returnhash;
                   7098: }
                   7099: 
1.1113    raeburn  7100: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7101: sub tmpdel {
                   7102:     my ($token,$server)=@_;
                   7103:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7104:     return &reply("tmpdel:$token",$server);
                   7105: }
                   7106: 
1.1172.2.13  raeburn  7107: # ------------------------------------------------------------ get_timebased_id
                   7108: 
                   7109: sub get_timebased_id {
                   7110:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7111:         $maxtries) = @_;
                   7112:     my ($newid,$error,$dellock);
                   7113:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7114:         return ('','ok','invalid call to get suffix');
                   7115:     }
                   7116: 
                   7117: # set defaults for any optional args for which values were not supplied
                   7118:     if ($who eq '') {
                   7119:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7120:     }
                   7121:     if (!$locktries) {
                   7122:         $locktries = 3;
                   7123:     }
                   7124:     if (!$maxtries) {
                   7125:         $maxtries = 10;
                   7126:     }
                   7127: 
                   7128:     if (($cdom eq '') || ($cnum eq '')) {
                   7129:         if ($env{'request.course.id'}) {
                   7130:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7131:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7132:         }
                   7133:         if (($cdom eq '') || ($cnum eq '')) {
                   7134:             return ('','ok','call to get suffix not in course context');
                   7135:         }
                   7136:     }
                   7137: 
                   7138: # construct locking item
                   7139:     my $lockhash = {
                   7140:                       $prefix."\0".'locked_'.$keyid => $who,
                   7141:                    };
                   7142:     my $tries = 0;
                   7143: 
                   7144: # attempt to get lock on nohist_$namespace file
                   7145:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7146:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7147:         $tries ++;
                   7148:         sleep 1;
                   7149:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7150:     }
                   7151: 
                   7152: # attempt to get unique identifier, based on current timestamp
                   7153:     if ($gotlock eq 'ok') {
                   7154:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7155:         my $id = time;
                   7156:         $newid = $id;
1.1172.2.56  raeburn  7157:         if ($idtype eq 'addcode') {
                   7158:             $newid .= &sixnum_code();
                   7159:         }
1.1172.2.13  raeburn  7160:         my $idtries = 0;
                   7161:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7162:             if ($idtype eq 'concat') {
                   7163:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7164:             } elsif ($idtype eq 'addcode') {
                   7165:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7166:             } else {
                   7167:                 $newid ++;
                   7168:             }
                   7169:             $idtries ++;
                   7170:         }
                   7171:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7172:             my %new_item =  (
                   7173:                               $prefix."\0".$newid => $who,
                   7174:                             );
                   7175:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7176:                                                  $cdom,$cnum);
                   7177:             if ($putresult ne 'ok') {
                   7178:                 undef($newid);
                   7179:                 $error = 'error saving new item: '.$putresult;
                   7180:             }
                   7181:         } else {
1.1172.2.56  raeburn  7182:              undef($newid);
1.1172.2.13  raeburn  7183:              $error = ('error: no unique suffix available for the new item ');
                   7184:         }
                   7185: #  remove lock
                   7186:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7187:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7188:     } else {
                   7189:         $error = "error: could not obtain lockfile\n";
                   7190:         $dellock = 'ok';
1.1172.2.58  raeburn  7191:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7192:             $dellock = 'nolock';
                   7193:         }
1.1172.2.13  raeburn  7194:     }
                   7195:     return ($newid,$dellock,$error);
                   7196: }
                   7197: 
1.1172.2.56  raeburn  7198: sub sixnum_code {
                   7199:     my $code;
                   7200:     for (0..6) {
                   7201:         $code .= int( rand(9) );
                   7202:     }
                   7203:     return $code;
                   7204: }
                   7205: 
1.765     albertel 7206: # -------------------------------------------------- portfolio access checking
                   7207: 
                   7208: sub portfolio_access {
1.1172.2.77  raeburn  7209:     my ($requrl,$clientip) = @_;
1.765     albertel 7210:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7211:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7212:     if ($result) {
                   7213:         my %setters;
                   7214:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7215:             my ($startblock,$endblock) =
                   7216:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7217:             if ($startblock && $endblock) {
                   7218:                 return 'B';
                   7219:             }
                   7220:         } else {
                   7221:             my ($startblock,$endblock) =
                   7222:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7223:             if ($startblock && $endblock) {
                   7224:                 return 'B';
                   7225:             }
                   7226:         }
                   7227:     }
1.765     albertel 7228:     if ($result eq 'ok') {
1.766     albertel 7229:        return 'F';
1.765     albertel 7230:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7231:        return 'A';
1.765     albertel 7232:     }
1.766     albertel 7233:     return '';
1.765     albertel 7234: }
                   7235: 
                   7236: sub get_portfolio_access {
1.1172.2.77  raeburn  7237:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7238: 
                   7239:     if (!ref($access_hash)) {
                   7240: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7241: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7242: 						   $file_name);
                   7243: 	$access_hash = $access_controls{$file_name};
                   7244:     }
                   7245: 
1.1172.2.77  raeburn  7246:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7247:     my $now = time;
                   7248:     if (ref($access_hash) eq 'HASH') {
                   7249:         foreach my $key (keys(%{$access_hash})) {
                   7250:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7251:             if ($start > $now) {
                   7252:                 next;
                   7253:             }
                   7254:             if ($end && $end<$now) {
                   7255:                 next;
                   7256:             }
                   7257:             if ($scope eq 'public') {
                   7258:                 $public = $key;
                   7259:                 last;
                   7260:             } elsif ($scope eq 'guest') {
                   7261:                 $guest = $key;
                   7262:             } elsif ($scope eq 'domains') {
                   7263:                 push(@domains,$key);
                   7264:             } elsif ($scope eq 'users') {
                   7265:                 push(@users,$key);
                   7266:             } elsif ($scope eq 'course') {
                   7267:                 push(@courses,$key);
                   7268:             } elsif ($scope eq 'group') {
                   7269:                 push(@groups,$key);
1.1172.2.77  raeburn  7270:             } elsif ($scope eq 'ip') {
                   7271:                 push(@ips,$key);
1.765     albertel 7272:             }
                   7273:         }
                   7274:         if ($public) {
                   7275:             return 'ok';
1.1172.2.77  raeburn  7276:         } elsif (@ips > 0) {
                   7277:             my $allowed;
                   7278:             foreach my $ipkey (@ips) {
                   7279:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7280:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7281:                         $allowed = 1;
                   7282:                         last;
                   7283:                     }
                   7284:                 }
                   7285:             }
                   7286:             if ($allowed) {
                   7287:                 return 'ok';
                   7288:             }
1.765     albertel 7289:         }
                   7290:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7291:             if ($guest) {
                   7292:                 return $guest;
                   7293:             }
                   7294:         } else {
                   7295:             if (@domains > 0) {
                   7296:                 foreach my $domkey (@domains) {
                   7297:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7298:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7299:                             return 'ok';
                   7300:                         }
                   7301:                     }
                   7302:                 }
                   7303:             }
                   7304:             if (@users > 0) {
                   7305:                 foreach my $userkey (@users) {
1.865     raeburn  7306:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7307:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7308:                             if (ref($item) eq 'HASH') {
                   7309:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7310:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7311:                                     return 'ok';
                   7312:                                 }
                   7313:                             }
                   7314:                         }
                   7315:                     } 
1.765     albertel 7316:                 }
                   7317:             }
                   7318:             my %roleshash;
                   7319:             my @courses_and_groups = @courses;
                   7320:             push(@courses_and_groups,@groups); 
                   7321:             if (@courses_and_groups > 0) {
                   7322:                 my (%allgroups,%allroles); 
                   7323:                 my ($start,$end,$role,$sec,$group);
                   7324:                 foreach my $envkey (%env) {
1.1060    raeburn  7325:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7326:                         my $cid = $2.'_'.$3; 
                   7327:                         if ($1 eq 'gr') {
                   7328:                             $group = $4;
                   7329:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7330:                         } else {
                   7331:                             if ($4 eq '') {
                   7332:                                 $sec = 'none';
                   7333:                             } else {
                   7334:                                 $sec = $4;
                   7335:                             }
                   7336:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7337:                         }
1.811     albertel 7338:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7339:                         my $cid = $2.'_'.$3;
                   7340:                         if ($4 eq '') {
                   7341:                             $sec = 'none';
                   7342:                         } else {
                   7343:                             $sec = $4;
                   7344:                         }
                   7345:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7346:                     }
                   7347:                 }
                   7348:                 if (keys(%allroles) == 0) {
                   7349:                     return;
                   7350:                 }
                   7351:                 foreach my $key (@courses_and_groups) {
                   7352:                     my %content = %{$$access_hash{$key}};
                   7353:                     my $cnum = $content{'number'};
                   7354:                     my $cdom = $content{'domain'};
                   7355:                     my $cid = $cdom.'_'.$cnum;
                   7356:                     if (!exists($allroles{$cid})) {
                   7357:                         next;
                   7358:                     }    
                   7359:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7360:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7361:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7362:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7363:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7364:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7365:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7366:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7367:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7368:                                         if (grep/^all$/,@sections) {
                   7369:                                             return 'ok';
                   7370:                                         } else {
                   7371:                                             if (grep/^$sec$/,@sections) {
                   7372:                                                 return 'ok';
                   7373:                                             }
                   7374:                                         }
                   7375:                                     }
                   7376:                                 }
                   7377:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7378:                                     if (grep/^none$/,@groups) {
                   7379:                                         return 'ok';
                   7380:                                     }
                   7381:                                 } else {
                   7382:                                     if (grep/^all$/,@groups) {
                   7383:                                         return 'ok';
                   7384:                                     } 
                   7385:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7386:                                         if (grep/^$group$/,@groups) {
                   7387:                                             return 'ok';
                   7388:                                         }
                   7389:                                     }
                   7390:                                 } 
                   7391:                             }
                   7392:                         }
                   7393:                     }
                   7394:                 }
                   7395:             }
                   7396:             if ($guest) {
                   7397:                 return $guest;
                   7398:             }
                   7399:         }
                   7400:     }
                   7401:     return;
                   7402: }
                   7403: 
                   7404: sub course_group_datechecker {
                   7405:     my ($dates,$now,$status) = @_;
                   7406:     my ($start,$end) = split(/\./,$dates);
                   7407:     if (!$start && !$end) {
                   7408:         return 'ok';
                   7409:     }
                   7410:     if (grep/^active$/,@{$status}) {
                   7411:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7412:             return 'ok';
                   7413:         }
                   7414:     }
                   7415:     if (grep/^previous$/,@{$status}) {
                   7416:         if ($end > $now ) {
                   7417:             return 'ok';
                   7418:         }
                   7419:     }
                   7420:     if (grep/^future$/,@{$status}) {
                   7421:         if ($start > $now) {
                   7422:             return 'ok';
                   7423:         }
                   7424:     }
                   7425:     return; 
                   7426: }
                   7427: 
                   7428: sub parse_portfolio_url {
                   7429:     my ($url) = @_;
                   7430: 
                   7431:     my ($type,$udom,$unum,$group,$file_name);
                   7432:     
1.823     albertel 7433:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7434: 	$type = 1;
                   7435:         $udom = $1;
                   7436:         $unum = $2;
                   7437:         $file_name = $3;
1.823     albertel 7438:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7439: 	$type = 2;
                   7440:         $udom = $1;
                   7441:         $unum = $2;
                   7442:         $group = $3;
                   7443:         $file_name = $3.'/'.$4;
                   7444:     }
                   7445:     if (wantarray) {
                   7446: 	return ($type,$udom,$unum,$file_name,$group);
                   7447:     }
                   7448:     return $type;
                   7449: }
                   7450: 
                   7451: sub is_portfolio_url {
                   7452:     my ($url) = @_;
                   7453:     return scalar(&parse_portfolio_url($url));
                   7454: }
                   7455: 
1.798     raeburn  7456: sub is_portfolio_file {
                   7457:     my ($file) = @_;
1.820     raeburn  7458:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7459:         return 1;
                   7460:     }
                   7461:     return;
                   7462: }
                   7463: 
1.976     raeburn  7464: sub usertools_access {
1.1084    raeburn  7465:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7466:     my ($access,%tools);
                   7467:     if ($context eq '') {
                   7468:         $context = 'tools';
                   7469:     }
                   7470:     if ($context eq 'requestcourses') {
                   7471:         %tools = (
                   7472:                       official   => 1,
                   7473:                       unofficial => 1,
1.1006    raeburn  7474:                       community  => 1,
1.1172.2.37  raeburn  7475:                       textbook   => 1,
1.985     raeburn  7476:                  );
1.1172.2.9  raeburn  7477:     } elsif ($context eq 'requestauthor') {
                   7478:         %tools = (
                   7479:                       requestauthor => 1,
                   7480:                  );
1.985     raeburn  7481:     } else {
                   7482:         %tools = (
                   7483:                       aboutme   => 1,
                   7484:                       blog      => 1,
1.1172.2.6  raeburn  7485:                       webdav    => 1,
1.985     raeburn  7486:                       portfolio => 1,
                   7487:                  );
                   7488:     }
1.976     raeburn  7489:     return if (!defined($tools{$tool}));
                   7490: 
1.1172.2.35  raeburn  7491:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7492:         $udom = $env{'user.domain'};
                   7493:         $uname = $env{'user.name'};
                   7494:     }
                   7495: 
1.978     raeburn  7496:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7497:         if ($action ne 'reload') {
1.985     raeburn  7498:             if ($context eq 'requestcourses') {
                   7499:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7500:             } elsif ($context eq 'requestauthor') {
                   7501:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7502:             } else {
                   7503:                 return $env{'environment.availabletools.'.$tool};
                   7504:             }
                   7505:         }
1.976     raeburn  7506:     }
                   7507: 
1.1172.2.9  raeburn  7508:     my ($toolstatus,$inststatus,$envkey);
                   7509:     if ($context eq 'requestauthor') {
                   7510:         $envkey = $context;
                   7511:     } else {
                   7512:         $envkey = $context.'.'.$tool;
                   7513:     }
1.976     raeburn  7514: 
1.985     raeburn  7515:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7516:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7517:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7518:         $inststatus = $env{'environment.inststatus'};
                   7519:     } else {
1.1084    raeburn  7520:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7521:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7522:             $inststatus = $userenvref->{'inststatus'};
                   7523:         } else {
1.1172.2.9  raeburn  7524:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7525:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7526:             $inststatus = $userenv{'inststatus'};
                   7527:         }
1.976     raeburn  7528:     }
                   7529: 
                   7530:     if ($toolstatus ne '') {
                   7531:         if ($toolstatus) {
                   7532:             $access = 1;
                   7533:         } else {
                   7534:             $access = 0;
                   7535:         }
                   7536:         return $access;
                   7537:     }
                   7538: 
1.1084    raeburn  7539:     my ($is_adv,%domdef);
                   7540:     if (ref($is_advref) eq 'HASH') {
                   7541:         $is_adv = $is_advref->{'is_adv'};
                   7542:     } else {
                   7543:         $is_adv = &is_advanced_user($udom,$uname);
                   7544:     }
                   7545:     if (ref($domdefref) eq 'HASH') {
                   7546:         %domdef = %{$domdefref};
                   7547:     } else {
                   7548:         %domdef = &get_domain_defaults($udom);
                   7549:     }
1.976     raeburn  7550:     if (ref($domdef{$tool}) eq 'HASH') {
                   7551:         if ($is_adv) {
                   7552:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7553:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7554:                     $access = 1;
                   7555:                 } else {
                   7556:                     $access = 0;
                   7557:                 }
                   7558:                 return $access;
                   7559:             }
                   7560:         }
                   7561:         if ($inststatus ne '') {
                   7562:             my ($hasaccess,$hasnoaccess);
                   7563:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7564:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7565:                     if ($domdef{$tool}{$affiliation}) {
                   7566:                         $hasaccess = 1;
                   7567:                     } else {
                   7568:                         $hasnoaccess = 1;
                   7569:                     }
                   7570:                 }
                   7571:             }
                   7572:             if ($hasaccess || $hasnoaccess) {
                   7573:                 if ($hasaccess) {
                   7574:                     $access = 1;
                   7575:                 } elsif ($hasnoaccess) {
                   7576:                     $access = 0; 
                   7577:                 }
                   7578:                 return $access;
                   7579:             }
                   7580:         } else {
                   7581:             if ($domdef{$tool}{'default'} ne '') {
                   7582:                 if ($domdef{$tool}{'default'}) {
                   7583:                     $access = 1;
                   7584:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7585:                     $access = 0;
                   7586:                 }
                   7587:                 return $access;
                   7588:             }
                   7589:         }
                   7590:     } else {
1.1172.2.6  raeburn  7591:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7592:             $access = 1;
                   7593:         } else {
                   7594:             $access = 0;
                   7595:         }
1.976     raeburn  7596:         return $access;
                   7597:     }
                   7598: }
                   7599: 
1.1050    raeburn  7600: sub is_course_owner {
                   7601:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7602:     if (($udom eq '') || ($uname eq '')) {
                   7603:         $udom = $env{'user.domain'};
                   7604:         $uname = $env{'user.name'};
                   7605:     }
                   7606:     unless (($udom eq '') || ($uname eq '')) {
                   7607:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7608:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7609:                 return 1;
                   7610:             } else {
                   7611:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7612:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7613:                     return 1;
                   7614:                 }
                   7615:             }
                   7616:         }
                   7617:     }
                   7618:     return;
                   7619: }
                   7620: 
1.976     raeburn  7621: sub is_advanced_user {
                   7622:     my ($udom,$uname) = @_;
1.1085    raeburn  7623:     if ($udom ne '' && $uname ne '') {
                   7624:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7625:             if (wantarray) {
                   7626:                 return ($env{'user.adv'},$env{'user.author'});
                   7627:             } else {
                   7628:                 return $env{'user.adv'};
                   7629:             }
1.1085    raeburn  7630:         }
                   7631:     }
1.976     raeburn  7632:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7633:     my %allroles;
1.1128    raeburn  7634:     my ($is_adv,$is_author);
1.976     raeburn  7635:     foreach my $role (keys(%roleshash)) {
                   7636:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7637:         my $area = '/'.$tdomain.'/'.$trest;
                   7638:         if ($sec ne '') {
                   7639:             $area .= '/'.$sec;
                   7640:         }
                   7641:         if (($area ne '') && ($trole ne '')) {
                   7642:             my $spec=$trole.'.'.$area;
                   7643:             if ($trole =~ /^cr\//) {
                   7644:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7645:             } elsif ($trole ne 'gr') {
                   7646:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7647:             }
1.1128    raeburn  7648:             if ($trole eq 'au') {
                   7649:                 $is_author = 1;
                   7650:             }
1.976     raeburn  7651:         }
                   7652:     }
                   7653:     foreach my $role (keys(%allroles)) {
                   7654:         last if ($is_adv);
                   7655:         foreach my $item (split(/:/,$allroles{$role})) {
                   7656:             if ($item ne '') {
                   7657:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7658:                 if ($privilege eq 'adv') {
                   7659:                     $is_adv = 1;
                   7660:                     last;
                   7661:                 }
                   7662:             }
                   7663:         }
                   7664:     }
1.1128    raeburn  7665:     if (wantarray) {
                   7666:         return ($is_adv,$is_author);
                   7667:     }
1.976     raeburn  7668:     return $is_adv;
                   7669: }
1.798     raeburn  7670: 
1.1035    raeburn  7671: sub check_can_request {
1.1036    raeburn  7672:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7673:     my $canreq = 0;
                   7674:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7675:     my @options = ('approval','validate','autolimit');
                   7676:     my $optregex = join('|',@options);
                   7677:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7678:         foreach my $type (@{$types}) {
                   7679:             if (&usertools_access($env{'user.name'},
                   7680:                                   $env{'user.domain'},
                   7681:                                   $type,undef,'requestcourses')) {
                   7682:                 $canreq ++;
1.1036    raeburn  7683:                 if (ref($request_domains) eq 'HASH') {
                   7684:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7685:                 }
1.1035    raeburn  7686:                 if ($dom eq $env{'user.domain'}) {
                   7687:                     $can_request->{$type} = 1;
                   7688:                 }
                   7689:             }
                   7690:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7691:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7692:                 if (@curr > 0) {
1.1036    raeburn  7693:                     foreach my $item (@curr) {
                   7694:                         if (ref($request_domains) eq 'HASH') {
                   7695:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7696:                             if ($otherdom ne '') {
                   7697:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7698:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7699:                                         push(@{$request_domains->{$type}},$otherdom);
                   7700:                                     }
                   7701:                                 } else {
                   7702:                                     push(@{$request_domains->{$type}},$otherdom);
                   7703:                                 }
                   7704:                             }
                   7705:                         }
                   7706:                     }
                   7707:                     unless($dom eq $env{'user.domain'}) {
                   7708:                         $canreq ++;
1.1035    raeburn  7709:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7710:                             $can_request->{$type} = 1;
                   7711:                         }
                   7712:                     }
                   7713:                 }
                   7714:             }
                   7715:         }
                   7716:     }
                   7717:     return $canreq;
                   7718: }
                   7719: 
1.341     www      7720: # ---------------------------------------------- Custom access rule evaluation
                   7721: 
                   7722: sub customaccess {
                   7723:     my ($priv,$uri)=@_;
1.807     albertel 7724:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7725:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7726:     $udom = &LONCAPA::clean_domain($udom);
                   7727:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7728:     my $access=0;
1.800     albertel 7729:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7730: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7731: 	if ($type eq 'user') {
                   7732: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7733: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7734: 		if ($tdom) {
                   7735: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7736: 		}
1.896     albertel 7737: 		if ($tuname) {
                   7738: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7739: 		}
                   7740: 		$access=($effect eq 'allow');
                   7741: 		last;
                   7742: 	    }
                   7743: 	} else {
                   7744: 	    if ($role) {
                   7745: 		if ($role ne $urole) { next; }
                   7746: 	    }
                   7747: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7748: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7749: 		if ($tdom) {
                   7750: 		    if ($tdom ne $udom) { next; }
                   7751: 		}
                   7752: 		if ($tcrs) {
                   7753: 		    if ($tcrs ne $ucrs) { next; }
                   7754: 		}
                   7755: 		if ($tsec) {
                   7756: 		    if ($tsec ne $usec) { next; }
                   7757: 		}
                   7758: 		$access=($effect eq 'allow');
                   7759: 		last;
                   7760: 	    }
                   7761: 	    if ($realm eq '' && $role eq '') {
                   7762: 		$access=($effect eq 'allow');
                   7763: 	    }
1.402     bowersj2 7764: 	}
1.341     www      7765:     }
                   7766:     return $access;
                   7767: }
                   7768: 
1.103     harris41 7769: # ------------------------------------------------- Check for a user privilege
1.12      www      7770: 
                   7771: sub allowed {
1.1172.2.65  raeburn  7772:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7773:     my $ver_orguri=$uri;
1.439     www      7774:     $uri=&deversion($uri);
1.152     www      7775:     my $orguri=$uri;
1.52      www      7776:     $uri=&declutter($uri);
1.809     raeburn  7777: 
1.810     raeburn  7778:     if ($priv eq 'evb') {
                   7779: # Evade communication block restrictions for specified role in a course
                   7780:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7781:             return $1;
                   7782:         } else {
                   7783:             return;
                   7784:         }
                   7785:     }
                   7786: 
1.620     albertel 7787:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7788: # Free bre access to adm and meta resources
1.1172.2.118.  .1(raebu 7789:20):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7790: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7791: 	&& ($priv eq 'bre')) {
1.14      www      7792: 	return 'F';
1.159     www      7793:     }
                   7794: 
1.545     banghart 7795: # Free bre access to user's own portfolio contents
1.714     raeburn  7796:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7797:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7798: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7799:         my %setters;
                   7800:         my ($startblock,$endblock) = 
                   7801:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7802:         if ($startblock && $endblock) {
                   7803:             return 'B';
                   7804:         } else {
                   7805:             return 'F';
                   7806:         }
1.545     banghart 7807:     }
                   7808: 
1.762     raeburn  7809: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7810:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7811:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7812:         if (exists($env{'request.course.id'})) {
                   7813:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7814:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7815:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7816:                 my $courseprivid=$env{'request.course.id'};
                   7817:                 $courseprivid=~s/\_/\//;
                   7818:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7819:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7820:                     return $1; 
1.762     raeburn  7821:                 } else {
                   7822:                     if ($env{'request.course.sec'}) {
                   7823:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7824:                     }
                   7825:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7826:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7827:                         return $2;
                   7828:                     }
1.714     raeburn  7829:                 }
                   7830:             }
                   7831:         }
                   7832:     }
                   7833: 
1.159     www      7834: # Free bre to public access
                   7835: 
                   7836:     if ($priv eq 'bre') {
1.238     www      7837:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7838: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7839:            return 'F'; 
                   7840:         }
1.238     www      7841:         if ($copyright eq 'priv') {
                   7842:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7843: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7844: 		return '';
                   7845:             }
                   7846:         }
                   7847:         if ($copyright eq 'domain') {
                   7848:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7849: 	    unless (($env{'user.domain'} eq $1) ||
                   7850:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7851: 		return '';
                   7852:             }
1.262     matthew  7853:         }
1.620     albertel 7854:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7855:             # Library role, so allow browsing of resources in this domain.
                   7856:             return 'F';
1.238     www      7857:         }
1.341     www      7858:         if ($copyright eq 'custom') {
                   7859: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7860:         }
1.14      www      7861:     }
1.264     matthew  7862:     # Domain coordinator is trying to create a course
1.620     albertel 7863:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7864:         # uri is the requested domain in this case.
                   7865:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7866:         # a role of dc for the domain in question.
1.620     albertel 7867:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7868:     }
1.29      www      7869: 
1.52      www      7870:     my $thisallowed='';
                   7871:     my $statecond=0;
                   7872:     my $courseprivid='';
                   7873: 
1.1039    raeburn  7874:     my $ownaccess;
1.1043    raeburn  7875:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7876:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7877:         if ($uri eq '') {
                   7878:             $ownaccess = 1;
                   7879:         } else {
                   7880:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7881:                 my $udom = $env{'user.domain'};
                   7882:                 my $uname = $env{'user.name'};
                   7883:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7884:                     $ownaccess = 1;
1.1040    raeburn  7885:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7886:                     unless ($uri =~ m{\.\./}) {
                   7887:                         $ownaccess = 1;
                   7888:                     }
                   7889:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7890:                     my $now = time;
                   7891:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7892:                         my $adom = $1;
                   7893:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7894:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7895:                                 my ($start,$end) = split('.',$env{$key});
                   7896:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7897:                                     $ownaccess = 1;
                   7898:                                     last;
                   7899:                                 }
                   7900:                             }
                   7901:                         }
                   7902:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7903:                         my $adom = $1;
                   7904:                         my $aname = $2;
1.1042    raeburn  7905:                         foreach my $role ('ca','aa') { 
                   7906:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7907:                                 my ($start,$end) =
                   7908:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7909:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7910:                                     $ownaccess = 1;
                   7911:                                     last;
                   7912:                                 }
1.1039    raeburn  7913:                             }
                   7914:                         }
                   7915:                     }
                   7916:                 }
                   7917:             }
                   7918:         }
                   7919:     }
                   7920: 
1.52      www      7921: # Course
                   7922: 
1.620     albertel 7923:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7924:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7925:             $thisallowed.=$1;
                   7926:         }
1.52      www      7927:     }
1.29      www      7928: 
1.52      www      7929: # Domain
                   7930: 
1.620     albertel 7931:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7932:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7933:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7934:             $thisallowed.=$1;
                   7935:         }
1.12      www      7936:     }
1.52      www      7937: 
1.1141    raeburn  7938: # User who is not author or co-author might still be able to edit
                   7939: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7940:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7941:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7942:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7943:             $thisallowed.=$1;
                   7944:         }
                   7945:     }
                   7946: 
1.52      www      7947: # Course: uri itself is a course
1.66      www      7948:     my $courseuri=$uri;
                   7949:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7950:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7951: 
1.620     albertel 7952:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7953:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  7954:         if ($priv eq 'mip') {
                   7955:             my $rem = $1;
                   7956:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   7957:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   7958:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7959:                 if ($cdom ne '') {
                   7960:                     my %passwdconf = &get_passwdconf($cdom);
                   7961:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   7962:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   7963:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   7964:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   7965:                                 unless (@inststatuses) {
                   7966:                                     @inststatuses = ('default');
                   7967:                                 }
                   7968:                                 foreach my $status (@inststatuses) {
                   7969:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   7970:                                         $thisallowed.=$rem;
                   7971:                                     }
                   7972:                                 }
                   7973:                             }
                   7974:                         }
                   7975:                     }
                   7976:                 }
                   7977:             }
                   7978:         } else {
                   7979:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   7980:                 $thisallowed.=$1;
                   7981:             }
1.1039    raeburn  7982:         }
1.12      www      7983:     }
1.29      www      7984: 
1.665     albertel 7985: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7986: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7987:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7988: 	$thisallowed='';
1.671     raeburn  7989:         my ($match)=&is_on_map($uri);
                   7990:         if ($match) {
                   7991:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7992:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7993:                 my $value = $1;
                   7994:                 if ($noblockcheck) {
                   7995:                     $thisallowed.=$value;
1.1162    raeburn  7996:                 } else {
1.1172.2.65  raeburn  7997:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7998:                     if (@blockers > 0) {
                   7999:                         $thisallowed = 'B';
                   8000:                     } else {
                   8001:                         $thisallowed.=$value;
                   8002:                     }
1.1162    raeburn  8003:                 }
1.671     raeburn  8004:             }
                   8005:         } else {
1.705     albertel 8006:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8007:             if ($refuri) {
                   8008:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8009:                     $thisallowed='F';
1.671     raeburn  8010:                 } else {
                   8011:                     $refuri=&declutter($refuri);
                   8012:                     my ($match) = &is_on_map($refuri);
                   8013:                     if ($match) {
1.1172.2.65  raeburn  8014:                         if ($noblockcheck) {
1.1162    raeburn  8015:                             $thisallowed='F';
1.1172.2.65  raeburn  8016:                         } else {
                   8017:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8018:                             if (@blockers > 0) {
                   8019:                                 $thisallowed = 'B';
                   8020:                             } else {
                   8021:                                 $thisallowed='F';
                   8022:                             }
1.1162    raeburn  8023:                         }
1.671     raeburn  8024:                     }
1.669     raeburn  8025:                 }
1.671     raeburn  8026:             }
                   8027:         }
1.314     www      8028:     }
1.492     albertel 8029: 
1.766     albertel 8030:     if ($priv eq 'bre'
                   8031: 	&& $thisallowed ne 'F' 
                   8032: 	&& $thisallowed ne '2'
                   8033: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8034: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8035:     }
                   8036:     
1.52      www      8037: # Full access at system, domain or course-wide level? Exit.
1.29      www      8038:     if ($thisallowed=~/F/) {
                   8039: 	return 'F';
                   8040:     }
                   8041: 
1.52      www      8042: # If this is generating or modifying users, exit with special codes
1.29      www      8043: 
1.643     www      8044:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8045: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8046: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8047: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8048: 	    unless ($auname) { return $thisallowed; }
                   8049: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8050: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8051: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8052: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8053: 	}
1.52      www      8054: 	return $thisallowed;
                   8055:     }
                   8056: #
1.103     harris41 8057: # Gathered so far: system, domain and course wide privileges
1.52      www      8058: #
                   8059: # Course: See if uri or referer is an individual resource that is part of 
                   8060: # the course
                   8061: 
1.620     albertel 8062:     if ($env{'request.course.id'}) {
1.232     www      8063: 
1.1172.2.115  raeburn  8064: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8065: 
                   8066:         if ($priv eq 'mip') {
                   8067:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8068:                 return $thisallowed;
                   8069:             } else {
                   8070:                 return '';
                   8071:             }
                   8072:         }
                   8073: 
1.620     albertel 8074:        $courseprivid=$env{'request.course.id'};
                   8075:        if ($env{'request.course.sec'}) {
                   8076:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8077:        }
                   8078:        $courseprivid=~s/\_/\//;
                   8079:        my $checkreferer=1;
1.232     www      8080:        my ($match,$cond)=&is_on_map($uri);
                   8081:        if ($match) {
                   8082:            $statecond=$cond;
1.620     albertel 8083:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8084:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8085:                my $value = $1;
                   8086:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8087:                    if ($noblockcheck) {
1.1162    raeburn  8088:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8089:                    } else {
                   8090:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8091:                        if (@blockers > 0) {
                   8092:                            $thisallowed = 'B';
                   8093:                        } else {
                   8094:                            $thisallowed.=$value;
                   8095:                        }
1.1162    raeburn  8096:                    }
                   8097:                } else {
                   8098:                    $thisallowed.=$value;
                   8099:                }
1.52      www      8100:                $checkreferer=0;
                   8101:            }
1.29      www      8102:        }
1.83      www      8103:        
1.148     www      8104:        if ($checkreferer) {
1.620     albertel 8105: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8106:             unless ($refuri) {
1.800     albertel 8107:                 foreach my $key (keys(%env)) {
                   8108: 		    if ($key=~/^httpref\..*\*/) {
                   8109: 			my $pattern=$key;
1.156     www      8110:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8111:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8112:                         $pattern=~s/\//\\\//g;
1.152     www      8113:                         if ($orguri=~/$pattern/) {
1.800     albertel 8114: 			    $refuri=$env{$key};
1.148     www      8115:                         }
                   8116:                     }
1.191     harris41 8117:                 }
1.148     www      8118:             }
1.232     www      8119: 
1.148     www      8120:          if ($refuri) { 
1.152     www      8121: 	  $refuri=&declutter($refuri);
1.232     www      8122:           my ($match,$cond)=&is_on_map($refuri);
                   8123:             if ($match) {
                   8124:               my $refstatecond=$cond;
1.620     albertel 8125:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8126:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8127:                   my $value = $1;
                   8128:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8129:                       if ($noblockcheck) {
1.1162    raeburn  8130:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8131:                       } else {
                   8132:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8133:                           if (@blockers > 0) {
                   8134:                               $thisallowed = 'B';
                   8135:                           } else {
                   8136:                               $thisallowed.=$value;
                   8137:                           }
1.1162    raeburn  8138:                       }
                   8139:                   } else {
                   8140:                       $thisallowed.=$value;
                   8141:                   }
1.53      www      8142:                   $uri=$refuri;
                   8143:                   $statecond=$refstatecond;
1.52      www      8144:               }
                   8145:           }
1.148     www      8146:         }
1.29      www      8147:        }
1.52      www      8148:    }
1.29      www      8149: 
1.52      www      8150: #
1.103     harris41 8151: # Gathered now: all privileges that could apply, and condition number
1.52      www      8152: # 
                   8153: #
                   8154: # Full or no access?
                   8155: #
1.29      www      8156: 
1.52      www      8157:     if ($thisallowed=~/F/) {
                   8158: 	return 'F';
                   8159:     }
1.29      www      8160: 
1.52      www      8161:     unless ($thisallowed) {
                   8162:         return '';
                   8163:     }
1.29      www      8164: 
1.52      www      8165: # Restrictions exist, deal with them
                   8166: #
                   8167: #   C:according to course preferences
                   8168: #   R:according to resource settings
                   8169: #   L:unless locked
                   8170: #   X:according to user session state
                   8171: #
                   8172: 
                   8173: # Possibly locked functionality, check all courses
1.54      www      8174: # Locks might take effect only after 10 minutes cache expiration for other
                   8175: # courses, and 2 minutes for current course
1.52      www      8176: 
                   8177:     my $envkey;
                   8178:     if ($thisallowed=~/L/) {
1.1000    raeburn  8179:         foreach $envkey (keys(%env)) {
1.54      www      8180:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8181:                my $courseid=$2;
                   8182:                my $roleid=$1.'.'.$2;
1.92      www      8183:                $courseid=~s/^\///;
1.54      www      8184:                my $expiretime=600;
1.620     albertel 8185:                if ($env{'request.role'} eq $roleid) {
1.54      www      8186: 		  $expiretime=120;
                   8187:                }
                   8188: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8189:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8190:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8191: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8192:                }
1.620     albertel 8193:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8194:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8195: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8196:                        &log($env{'user.domain'},$env{'user.name'},
                   8197:                             $env{'user.home'},
1.57      www      8198:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8199:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8200:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8201: 		       return '';
                   8202:                    }
                   8203:                }
1.620     albertel 8204:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8205:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8206: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8207:                        &log($env{'user.domain'},$env{'user.name'},
                   8208:                             $env{'user.home'},
1.57      www      8209:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8210:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8211:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8212: 		       return '';
                   8213:                    }
                   8214:                }
                   8215: 	   }
1.29      www      8216:        }
1.52      www      8217:     }
                   8218:    
                   8219: #
                   8220: # Rest of the restrictions depend on selected course
                   8221: #
                   8222: 
1.620     albertel 8223:     unless ($env{'request.course.id'}) {
1.766     albertel 8224: 	if ($thisallowed eq 'A') {
                   8225: 	    return 'A';
1.814     raeburn  8226:         } elsif ($thisallowed eq 'B') {
                   8227:             return 'B';
1.766     albertel 8228: 	} else {
                   8229: 	    return '1';
                   8230: 	}
1.52      www      8231:     }
1.29      www      8232: 
1.52      www      8233: #
                   8234: # Now user is definitely in a course
                   8235: #
1.53      www      8236: 
                   8237: 
                   8238: # Course preferences
                   8239: 
                   8240:    if ($thisallowed=~/C/) {
1.620     albertel 8241:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8242:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8243:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8244: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8245: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8246: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8247: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8248: 			$env{'request.course.id'});
                   8249: 	   }
1.237     www      8250:            return '';
                   8251:        }
                   8252: 
1.620     albertel 8253:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8254: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8255: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8256: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8257: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8258: 			$env{'request.course.id'});
                   8259: 	   }
1.54      www      8260:            return '';
                   8261:        }
1.53      www      8262:    }
                   8263: 
                   8264: # Resource preferences
                   8265: 
                   8266:    if ($thisallowed=~/R/) {
1.620     albertel 8267:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8268:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8269: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8270: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8271: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8272: 	   }
                   8273: 	   return '';
1.54      www      8274:        }
1.53      www      8275:    }
1.30      www      8276: 
1.246     www      8277: # Restricted by state or randomout?
1.30      www      8278: 
1.52      www      8279:    if ($thisallowed=~/X/) {
1.620     albertel 8280:       if ($env{'acc.randomout'}) {
1.579     albertel 8281: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8282:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8283:             return ''; 
                   8284:          }
1.247     www      8285:       }
                   8286:       if (&condval($statecond)) {
1.52      www      8287: 	 return '2';
                   8288:       } else {
                   8289:          return '';
                   8290:       }
                   8291:    }
1.30      www      8292: 
1.766     albertel 8293:     if ($thisallowed eq 'A') {
                   8294: 	return 'A';
1.814     raeburn  8295:     } elsif ($thisallowed eq 'B') {
                   8296:         return 'B';
1.766     albertel 8297:     }
1.52      www      8298:    return 'F';
1.232     www      8299: }
1.1162    raeburn  8300: 
1.1172.2.13  raeburn  8301: # ------------------------------------------- Check construction space access
                   8302: 
                   8303: sub constructaccess {
                   8304:     my ($url,$setpriv)=@_;
                   8305: 
                   8306: # We do not allow editing of previous versions of files
                   8307:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8308: 
                   8309: # Get username and domain from URL
                   8310:     my ($ownername,$ownerdomain,$ownerhome);
                   8311: 
                   8312:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8313:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8314: 
                   8315: # The URL does not really point to any authorspace, forget it
                   8316:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8317: 
                   8318: # Now we need to see if the user has access to the authorspace of
                   8319: # $ownername at $ownerdomain
                   8320: 
                   8321:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8322: # Real author for this?
                   8323:        $ownerhome = $env{'user.home'};
                   8324:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8325:           return ($ownername,$ownerdomain,$ownerhome);
                   8326:        }
                   8327:     } else {
                   8328: # Co-author for this?
                   8329:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8330:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8331:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8332:             return ($ownername,$ownerdomain,$ownerhome);
                   8333:         }
                   8334:     }
                   8335: 
                   8336: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8337: # we might as well leave
                   8338:    unless ($setpriv) { return ''; }
                   8339: 
                   8340: # Backdoor access?
                   8341:     my $allowed=&allowed('eco',$ownerdomain);
                   8342: # Nope
                   8343:     unless ($allowed) { return ''; }
                   8344: # Looks like we may have access, but could be locked by the owner of the construction space
                   8345:     if ($allowed eq 'U') {
                   8346:         my %blocked=&get('environment',['domcoord.author'],
                   8347:                          $ownerdomain,$ownername);
                   8348: # Is blocked by owner
                   8349:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8350:     }
                   8351:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8352: # Grant temporary access
                   8353:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8354:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8355:         if (!$update) { $update = $then; }
                   8356:         my $refresh=$env{'user.refresh.time'};
                   8357:         if (!$refresh) { $refresh = $update; }
                   8358:         my $now = time;
                   8359:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8360:                            $now,'ca','constructaccess');
                   8361:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8362:         return($ownername,$ownerdomain,$ownerhome);
                   8363:     }
                   8364: # No business here
                   8365:     return '';
                   8366: }
                   8367: 
1.1172.2.66  raeburn  8368: # ----------------------------------------------------------- Content Blocking
                   8369: 
                   8370: {
                   8371: # Caches for faster Course Contents display where content blocking
                   8372: # is in operation (i.e., interval param set) for timed quiz.
                   8373: #
                   8374: # User for whom data are being temporarily cached.
                   8375: my $cacheduser='';
                   8376: # Cached blockers for this user (a hash of blocking items).
                   8377: my %cachedblockers=();
                   8378: # When the data were last cached.
                   8379: my $cachedlast='';
                   8380: 
                   8381: sub load_all_blockers {
                   8382:     my ($uname,$udom,$blocks)=@_;
                   8383:     if (($uname ne '') && ($udom ne '')) {
                   8384:         if (($cacheduser eq $uname.':'.$udom) &&
                   8385:             (abs($cachedlast-time)<5)) {
                   8386:             return;
                   8387:         }
                   8388:     }
                   8389:     $cachedlast=time;
                   8390:     $cacheduser=$uname.':'.$udom;
                   8391:     %cachedblockers = &get_commblock_resources($blocks);
                   8392: }
                   8393: 
1.1162    raeburn  8394: sub get_comm_blocks {
                   8395:     my ($cdom,$cnum) = @_;
                   8396:     if ($cdom eq '' || $cnum eq '') {
                   8397:         return unless ($env{'request.course.id'});
                   8398:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8399:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8400:     }
                   8401:     my %commblocks;
                   8402:     my $hashid=$cdom.'_'.$cnum;
                   8403:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8404:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8405:         %commblocks = %{$blocksref};
                   8406:     } else {
                   8407:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8408:         my $cachetime = 600;
                   8409:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8410:     }
                   8411:     return %commblocks;
                   8412: }
                   8413: 
1.1172.2.66  raeburn  8414: sub get_commblock_resources {
                   8415:     my ($blocks) = @_;
                   8416:     my %blockers = ();
                   8417:     return %blockers unless ($env{'request.course.id'});
                   8418:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8419:     my %commblocks;
                   8420:     if (ref($blocks) eq 'HASH') {
                   8421:         %commblocks = %{$blocks};
                   8422:     } else {
                   8423:         %commblocks = &get_comm_blocks();
                   8424:     }
1.1172.2.66  raeburn  8425:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8426:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8427:     return %blockers unless (ref($navmap));
                   8428:     my $now = time;
1.1162    raeburn  8429:     foreach my $block (keys(%commblocks)) {
                   8430:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8431:             my ($start,$end) = ($1,$2);
                   8432:             if ($start <= $now && $end >= $now) {
                   8433:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8434:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8435:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8436:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8437:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8438:                             }
                   8439:                         }
                   8440:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8441:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8442:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8443:                             }
                   8444:                         }
                   8445:                     }
                   8446:                 }
                   8447:             }
                   8448:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8449:             my $item = $1;
1.1163    raeburn  8450:             my @to_test;
1.1162    raeburn  8451:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8452:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8453:                     my @interval;
                   8454:                     my $type = 'map';
                   8455:                     if ($item eq 'course') {
                   8456:                         $type = 'course';
                   8457:                         @interval=&EXT("resource.0.interval");
                   8458:                     } else {
                   8459:                         if ($item =~ /___\d+___/) {
                   8460:                             $type = 'resource';
                   8461:                             @interval=&EXT("resource.0.interval",$item);
                   8462:                             if (ref($navmap)) {
                   8463:                                 my $res = $navmap->getBySymb($item);
                   8464:                                 push(@to_test,$res);
                   8465:                             }
1.1162    raeburn  8466:                         } else {
1.1172.2.66  raeburn  8467:                             my $mapsymb = &symbread($item,1);
                   8468:                             if ($mapsymb) {
                   8469:                                 if (ref($navmap)) {
                   8470:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8471:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8472:                                     foreach my $res (@to_test) {
                   8473:                                         my $symb = $res->symb();
                   8474:                                         next if ($symb eq $mapsymb);
                   8475:                                         if ($symb ne '') {
                   8476:                                             @interval=&EXT("resource.0.interval",$symb);
                   8477:                                             if ($interval[1] eq 'map') {
                   8478:                                                 last;
1.1162    raeburn  8479:                                             }
                   8480:                                         }
                   8481:                                     }
                   8482:                                 }
                   8483:                             }
                   8484:                         }
1.1172.2.66  raeburn  8485:                     }
1.1172.2.118.  .1(raebu 8486:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8487:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8488:                         my $first_access;
                   8489:                         if ($type eq 'resource') {
                   8490:                             $first_access=&get_first_access($interval[1],$item);
                   8491:                         } elsif ($type eq 'map') {
                   8492:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8493:                         } else {
                   8494:                             $first_access=&get_first_access($interval[1]);
                   8495:                         }
                   8496:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8497:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8498:                             if ($timesup > $now) {
                   8499:                                 my $activeblock;
                   8500:                                 foreach my $res (@to_test) {
                   8501:                                     if ($res->answerable()) {
                   8502:                                         $activeblock = 1;
                   8503:                                         last;
                   8504:                                     }
                   8505:                                 }
                   8506:                                 if ($activeblock) {
                   8507:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8508:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8509:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8510:                                          }
                   8511:                                     }
                   8512:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8513:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8514:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8515:                                         }
1.1162    raeburn  8516:                                     }
                   8517:                                 }
                   8518:                             }
                   8519:                         }
                   8520:                     }
                   8521:                 }
                   8522:             }
                   8523:         }
                   8524:     }
1.1172.2.66  raeburn  8525:     return %blockers;
1.1162    raeburn  8526: }
                   8527: 
1.1172.2.66  raeburn  8528: sub has_comm_blocking {
                   8529:     my ($priv,$symb,$uri,$blocks) = @_;
                   8530:     my @blockers;
                   8531:     return unless ($env{'request.course.id'});
                   8532:     return unless ($priv eq 'bre');
                   8533:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8534:     return if ($env{'request.state'} eq 'construct');
                   8535:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8536:     return unless (keys(%cachedblockers) > 0);
                   8537:     my (%possibles,@symbs);
                   8538:     if (!$symb) {
                   8539:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8540:     }
1.1172.2.66  raeburn  8541:     if ($symb) {
                   8542:         @symbs = ($symb);
                   8543:     } elsif (keys(%possibles)) {
                   8544:         @symbs = keys(%possibles);
                   8545:     }
                   8546:     my $noblock;
                   8547:     foreach my $symb (@symbs) {
                   8548:         last if ($noblock);
                   8549:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8550:         foreach my $block (keys(%cachedblockers)) {
                   8551:             if ($block =~ /^firstaccess____(.+)$/) {
                   8552:                 my $item = $1;
                   8553:                 if (($item eq $map) || ($item eq $symb)) {
                   8554:                     $noblock = 1;
                   8555:                     last;
                   8556:                 }
1.1162    raeburn  8557:             }
1.1172.2.66  raeburn  8558:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8559:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8560:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8561:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8562:                             push(@blockers,$block);
                   8563:                         }
                   8564:                     }
                   8565:                 }
                   8566:             }
                   8567:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8568:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8569:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8570:                         push(@blockers,$block);
                   8571:                     }
                   8572:                 }
1.1162    raeburn  8573:             }
                   8574:         }
                   8575:     }
1.1172.2.66  raeburn  8576:     return if ($noblock);
                   8577:     return @blockers;
                   8578: }
1.1162    raeburn  8579: }
                   8580: 
1.1172.2.66  raeburn  8581: # -------------------------------- Deversion and split uri into path an filename
                   8582: 
1.1133    foxr     8583: #
1.1172.2.66  raeburn  8584: #   Removes the version from a URI and
1.1133    foxr     8585: #   splits it in to its filename and path to the filename.
                   8586: #   Seems like File::Basename could have done this more clearly.
                   8587: #   Parameters:
                   8588: #      $uri   - input URI
                   8589: #   Returns:
                   8590: #     Two element list consisting of 
                   8591: #     $pathname  - the URI up to and excluding the trailing /
                   8592: #     $filename  - The part of the URI following the last /
                   8593: #  NOTE:
                   8594: #    Another realization of this is simply:
                   8595: #    use File::Basename;
                   8596: #    ...
                   8597: #    $uri = shift;
                   8598: #    $filename = basename($uri);
                   8599: #    $path     = dirname($uri);
                   8600: #    return ($filename, $path);
                   8601: #
                   8602: #     The implementation below is probably faster however.
                   8603: #
1.710     albertel 8604: sub split_uri_for_cond {
                   8605:     my $uri=&deversion(&declutter(shift));
                   8606:     my @uriparts=split(/\//,$uri);
                   8607:     my $filename=pop(@uriparts);
                   8608:     my $pathname=join('/',@uriparts);
                   8609:     return ($pathname,$filename);
                   8610: }
1.232     www      8611: # --------------------------------------------------- Is a resource on the map?
                   8612: 
                   8613: sub is_on_map {
1.710     albertel 8614:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8615:     #Trying to find the conditional for the file
1.620     albertel 8616:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8617: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8618:     if ($match) {
1.289     bowersj2 8619: 	return (1,$1);
                   8620:     } else {
1.434     www      8621: 	return (0,0);
1.289     bowersj2 8622:     }
1.12      www      8623: }
                   8624: 
1.427     www      8625: # --------------------------------------------------------- Get symb from alias
                   8626: 
                   8627: sub get_symb_from_alias {
                   8628:     my $symb=shift;
                   8629:     my ($map,$resid,$url)=&decode_symb($symb);
                   8630: # Already is a symb
                   8631:     if ($url) { return $symb; }
                   8632: # Must be an alias
                   8633:     my $aliassymb='';
                   8634:     my %bighash;
1.620     albertel 8635:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8636:                             &GDBM_READER(),0640)) {
                   8637:         my $rid=$bighash{'mapalias_'.$symb};
                   8638: 	if ($rid) {
                   8639: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8640: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8641: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8642: 	}
                   8643:         untie %bighash;
                   8644:     }
                   8645:     return $aliassymb;
                   8646: }
                   8647: 
1.12      www      8648: # ----------------------------------------------------------------- Define Role
                   8649: 
                   8650: sub definerole {
                   8651:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8652:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8653:     foreach my $role (split(':',$sysrole)) {
                   8654: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8655:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8656:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8657: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8658:                return "refused:s:$crole&$cqual"; 
                   8659:             }
                   8660:         }
1.191     harris41 8661:     }
1.800     albertel 8662:     foreach my $role (split(':',$domrole)) {
                   8663: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8664:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8665:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8666: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8667:                return "refused:d:$crole&$cqual"; 
                   8668:             }
                   8669:         }
1.191     harris41 8670:     }
1.800     albertel 8671:     foreach my $role (split(':',$courole)) {
                   8672: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8673:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8674:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8675: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8676:                return "refused:c:$crole&$cqual"; 
                   8677:             }
                   8678:         }
1.191     harris41 8679:     }
1.1172.2.84  raeburn  8680:     my $uhome;
                   8681:     if (($uname ne '') && ($udom ne '')) {
                   8682:         $uhome = &homeserver($uname,$udom);
                   8683:         return $uhome if ($uhome eq 'no_host');
                   8684:     } else {
                   8685:         $uname = $env{'user.name'};
                   8686:         $udom = $env{'user.domain'};
                   8687:         $uhome = $env{'user.home'};
                   8688:     }
1.620     albertel 8689:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8690:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8691:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8692:     return reply($command,$uhome);
1.12      www      8693:   } else {
                   8694:     return 'refused';
                   8695:   }
1.105     harris41 8696: }
                   8697: 
                   8698: # ---------------- Make a metadata query against the network of library servers
                   8699: 
                   8700: sub metadata_query {
1.1172.2.33  raeburn  8701:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8702:     my %rhash;
1.845     albertel 8703:     my %libserv = &all_library();
1.244     matthew  8704:     my @server_list = (defined($server_array) ? @$server_array
                   8705:                                               : keys(%libserv) );
                   8706:     for my $server (@server_list) {
1.1172.2.33  raeburn  8707:         my $domains = '';
                   8708:         if (ref($domains_hash) eq 'HASH') {
                   8709:             $domains = $domains_hash->{$server};    
                   8710:         }
1.118     harris41 8711: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8712: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8713: 	    $rhash{$server}=$reply;
                   8714: 	}
                   8715: 	else {
                   8716: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8717: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8718: 			     $server);
                   8719: 	    $rhash{$server}=$reply;
                   8720: 	}
1.112     harris41 8721:     }
1.118     harris41 8722:     return \%rhash;
1.240     www      8723: }
                   8724: 
                   8725: # ----------------------------------------- Send log queries and wait for reply
                   8726: 
                   8727: sub log_query {
                   8728:     my ($uname,$udom,$query,%filters)=@_;
                   8729:     my $uhome=&homeserver($uname,$udom);
                   8730:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8731:     my $uhost=&hostname($uhome);
1.800     albertel 8732:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8733:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8734:                        $uhome);
1.479     albertel 8735:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8736:     return get_query_reply($queryid);
                   8737: }
                   8738: 
1.818     raeburn  8739: # -------------------------- Update MySQL table for portfolio file
                   8740: 
                   8741: sub update_portfolio_table {
1.821     raeburn  8742:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8743:     if ($group ne '') {
                   8744:         $file_name =~s /^\Q$group\E//;
                   8745:     }
1.818     raeburn  8746:     my $homeserver = &homeserver($uname,$udom);
                   8747:     my $queryid=
1.821     raeburn  8748:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8749:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8750:     my $reply = &get_query_reply($queryid);
                   8751:     return $reply;
                   8752: }
                   8753: 
1.899     raeburn  8754: # -------------------------- Update MySQL allusers table
                   8755: 
                   8756: sub update_allusers_table {
                   8757:     my ($uname,$udom,$names) = @_;
                   8758:     my $homeserver = &homeserver($uname,$udom);
                   8759:     my $queryid=
                   8760:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8761:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8762:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8763:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8764:                'generation='.&escape($names->{'generation'}).'%%'.
                   8765:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8766:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8767:     return;
1.899     raeburn  8768: }
                   8769: 
1.508     raeburn  8770: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8771: 
                   8772: sub fetch_enrollment_query {
1.511     raeburn  8773:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8774:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8775:     my $maxtries = 1;
1.508     raeburn  8776:     if ($context eq 'automated') {
                   8777:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8778:         $sleep = 2;
                   8779:         $loopmax = 100;
1.547     raeburn  8780:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8781:     } else {
                   8782:         $homeserver = &homeserver($cnum,$dom);
                   8783:     }
1.838     albertel 8784:     my $host=&hostname($homeserver);
1.506     raeburn  8785:     my $cmd = '';
1.1000    raeburn  8786:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8787:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8788:     }
                   8789:     $cmd =~ s/%%$//;
                   8790:     $cmd = &escape($cmd);
                   8791:     my $query = 'fetchenrollment';
1.620     albertel 8792:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8793:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8794:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8795:         return 'error: '.$queryid;
                   8796:     }
1.1172.2.93  raeburn  8797:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8798:     my $tries = 1;
                   8799:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8800:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8801:         $tries ++;
                   8802:     }
1.526     raeburn  8803:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8804:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8805:     } else {
1.901     albertel 8806:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8807:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8808:             foreach my $line (@responses) {
                   8809:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8810:                 $$replyref{$key} = $value;
                   8811:             }
                   8812:         } else {
1.1117    foxr     8813:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8814:             foreach my $line (@responses) {
                   8815:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8816:                 $$replyref{$key} = $value;
                   8817:                 if ($value > 0) {
1.800     albertel 8818:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8819:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8820:                         my $destname = $pathname.'/'.$filename;
                   8821:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8822:                         if ($xml_classlist =~ /^error/) {
                   8823:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8824:                         } else {
1.1172.2.96  raeburn  8825:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8826:                                 print FILE &unescape($xml_classlist);
                   8827:                                 close(FILE);
1.526     raeburn  8828:                             } else {
                   8829:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8830:                             }
                   8831:                         }
                   8832:                     }
                   8833:                 }
                   8834:             }
                   8835:         }
                   8836:         return 'ok';
                   8837:     }
                   8838:     return 'error';
                   8839: }
                   8840: 
1.242     www      8841: sub get_query_reply {
1.1172.2.79  raeburn  8842:     my ($queryid,$sleep,$loopmax) = @_;
                   8843:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8844:         $sleep = 0.2;
                   8845:     }
                   8846:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8847:         $loopmax = 100;
                   8848:     }
1.1117    foxr     8849:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8850:     my $reply='';
1.1172.2.79  raeburn  8851:     for (1..$loopmax) {
                   8852: 	sleep($sleep);
1.240     www      8853:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8854: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8855: 		$reply = join('',<$fh>);
                   8856: 		close($fh);
1.240     www      8857: 	   } else { return 'error: reply_file_error'; }
1.242     www      8858:            return &unescape($reply);
                   8859: 	}
1.240     www      8860:     }
1.242     www      8861:     return 'timeout:'.$queryid;
1.240     www      8862: }
                   8863: 
                   8864: sub courselog_query {
1.241     www      8865: #
                   8866: # possible filters:
                   8867: # url: url or symb
                   8868: # username
                   8869: # domain
                   8870: # action: view, submit, grade
                   8871: # start: timestamp
                   8872: # end: timestamp
                   8873: #
1.240     www      8874:     my (%filters)=@_;
1.620     albertel 8875:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8876:     if ($filters{'url'}) {
                   8877: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8878:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8879:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8880:     }
1.620     albertel 8881:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8882:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8883:     return &log_query($cname,$cdom,'courselog',%filters);
                   8884: }
                   8885: 
                   8886: sub userlog_query {
1.858     raeburn  8887: #
                   8888: # possible filters:
                   8889: # action: log check role
                   8890: # start: timestamp
                   8891: # end: timestamp
                   8892: #
1.240     www      8893:     my ($uname,$udom,%filters)=@_;
                   8894:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8895: }
                   8896: 
1.506     raeburn  8897: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8898: 
                   8899: sub auto_run {
1.508     raeburn  8900:     my ($cnum,$cdom) = @_;
1.876     raeburn  8901:     my $response = 0;
                   8902:     my $settings;
                   8903:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8904:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8905:         $settings = $domconfig{'autoenroll'};
                   8906:         if ($settings->{'run'} eq '1') {
                   8907:             $response = 1;
                   8908:         }
                   8909:     } else {
1.934     raeburn  8910:         my $homeserver;
                   8911:         if (&is_course($cdom,$cnum)) {
                   8912:             $homeserver = &homeserver($cnum,$cdom);
                   8913:         } else {
                   8914:             $homeserver = &domain($cdom,'primary');
                   8915:         }
                   8916:         if ($homeserver ne 'no_host') {
                   8917:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8918:         }
1.876     raeburn  8919:     }
1.506     raeburn  8920:     return $response;
                   8921: }
1.776     albertel 8922: 
1.506     raeburn  8923: sub auto_get_sections {
1.508     raeburn  8924:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8925:     my $homeserver;
                   8926:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8927:         $homeserver = &homeserver($cnum,$cdom);
                   8928:     }
                   8929:     if (!defined($homeserver)) { 
                   8930:         if ($cdom =~ /^$match_domain$/) {
                   8931:             $homeserver = &domain($cdom,'primary');
                   8932:         }
                   8933:     }
                   8934:     my @secs;
                   8935:     if (defined($homeserver)) {
                   8936:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8937:         unless ($response eq 'refused') {
                   8938:             @secs = split(/:/,$response);
                   8939:         }
1.506     raeburn  8940:     }
                   8941:     return @secs;
                   8942: }
1.776     albertel 8943: 
1.506     raeburn  8944: sub auto_new_course {
1.1099    raeburn  8945:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8946:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8947:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8948:     return $response;
                   8949: }
1.776     albertel 8950: 
1.506     raeburn  8951: sub auto_validate_courseID {
1.508     raeburn  8952:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8953:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8954:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8955:     return $response;
                   8956: }
1.776     albertel 8957: 
1.1007    raeburn  8958: sub auto_validate_instcode {
1.1020    raeburn  8959:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8960:     my ($homeserver,$response);
                   8961:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8962:         $homeserver = &homeserver($cnum,$cdom);
                   8963:     }
                   8964:     if (!defined($homeserver)) {
                   8965:         if ($cdom =~ /^$match_domain$/) {
                   8966:             $homeserver = &domain($cdom,'primary');
                   8967:         }
                   8968:     }
1.1065    raeburn  8969:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8970:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8971:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8972:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8973: }
                   8974: 
1.506     raeburn  8975: sub auto_create_password {
1.873     raeburn  8976:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8977:     my ($homeserver,$response);
1.506     raeburn  8978:     my $create_passwd = 0;
                   8979:     my $authchk = '';
1.873     raeburn  8980:     if ($udom =~ /^$match_domain$/) {
                   8981:         $homeserver = &domain($udom,'primary');
                   8982:     }
                   8983:     if ($homeserver eq '') {
                   8984:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8985:             $homeserver = &homeserver($cnum,$cdom);
                   8986:         }
                   8987:     }
                   8988:     if ($homeserver eq '') {
                   8989:         $authchk = 'nodomain';
1.506     raeburn  8990:     } else {
1.873     raeburn  8991:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8992:         if ($response eq 'refused') {
                   8993:             $authchk = 'refused';
                   8994:         } else {
1.901     albertel 8995:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8996:         }
1.506     raeburn  8997:     }
                   8998:     return ($authparam,$create_passwd,$authchk);
                   8999: }
                   9000: 
1.706     raeburn  9001: sub auto_photo_permission {
                   9002:     my ($cnum,$cdom,$students) = @_;
                   9003:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9004:     my ($outcome,$perm_reqd,$conditions) = 
                   9005: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9006:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9007: 	return (undef,undef);
                   9008:     }
1.706     raeburn  9009:     return ($outcome,$perm_reqd,$conditions);
                   9010: }
                   9011: 
                   9012: sub auto_checkphotos {
                   9013:     my ($uname,$udom,$pid) = @_;
                   9014:     my $homeserver = &homeserver($uname,$udom);
                   9015:     my ($result,$resulttype);
                   9016:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9017: 				   &escape($uname).':'.&escape($pid),
                   9018: 				   $homeserver));
1.709     albertel 9019:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9020: 	return (undef,undef);
                   9021:     }
1.706     raeburn  9022:     if ($outcome) {
                   9023:         ($result,$resulttype) = split(/:/,$outcome);
                   9024:     } 
                   9025:     return ($result,$resulttype);
                   9026: }
                   9027: 
                   9028: sub auto_photochoice {
                   9029:     my ($cnum,$cdom) = @_;
                   9030:     my $homeserver = &homeserver($cnum,$cdom);
                   9031:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9032: 						       &escape($cdom),
                   9033: 						       $homeserver)));
1.709     albertel 9034:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9035: 	return (undef,undef);
                   9036:     }
1.706     raeburn  9037:     return ($update,$comment);
                   9038: }
                   9039: 
                   9040: sub auto_photoupdate {
                   9041:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9042:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9043:     my $host=&hostname($homeserver);
1.706     raeburn  9044:     my $cmd = '';
                   9045:     my $maxtries = 1;
1.800     albertel 9046:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9047:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9048:     }
                   9049:     $cmd =~ s/%%$//;
                   9050:     $cmd = &escape($cmd);
                   9051:     my $query = 'institutionalphotos';
                   9052:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9053:     unless ($queryid=~/^\Q$host\E\_/) {
                   9054:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9055:         return 'error: '.$queryid;
                   9056:     }
                   9057:     my $reply = &get_query_reply($queryid);
                   9058:     my $tries = 1;
                   9059:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9060:         $reply = &get_query_reply($queryid);
                   9061:         $tries ++;
                   9062:     }
                   9063:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9064:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9065:     } else {
                   9066:         my @responses = split(/:/,$reply);
                   9067:         my $outcome = shift(@responses); 
                   9068:         foreach my $item (@responses) {
                   9069:             my ($key,$value) = split(/=/,$item);
                   9070:             $$photo{$key} = $value;
                   9071:         }
                   9072:         return $outcome;
                   9073:     }
                   9074:     return 'error';
                   9075: }
                   9076: 
1.521     raeburn  9077: sub auto_instcode_format {
1.793     albertel 9078:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9079: 	$cat_order) = @_;
1.521     raeburn  9080:     my $courses = '';
1.772     raeburn  9081:     my @homeservers;
1.521     raeburn  9082:     if ($caller eq 'global') {
1.841     albertel 9083: 	my %servers = &get_servers($codedom,'library');
                   9084: 	foreach my $tryserver (keys(%servers)) {
                   9085: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9086: 		push(@homeservers,$tryserver);
                   9087: 	    }
1.584     raeburn  9088:         }
1.1022    raeburn  9089:     } elsif ($caller eq 'requests') {
                   9090:         if ($codedom =~ /^$match_domain$/) {
                   9091:             my $chome = &domain($codedom,'primary');
                   9092:             unless ($chome eq 'no_host') {
                   9093:                 push(@homeservers,$chome);
                   9094:             }
                   9095:         }
1.521     raeburn  9096:     } else {
1.772     raeburn  9097:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9098:     }
1.793     albertel 9099:     foreach my $code (keys(%{$instcodes})) {
                   9100:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9101:     }
                   9102:     chop($courses);
1.772     raeburn  9103:     my $ok_response = 0;
                   9104:     my $response;
                   9105:     while (@homeservers > 0 && $ok_response == 0) {
                   9106:         my $server = shift(@homeservers); 
                   9107:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9108:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9109:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9110: 		split(/:/,$response);
1.772     raeburn  9111:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9112:             push(@{$codetitles},&str2array($codetitles_str));
                   9113:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9114:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9115:             $ok_response = 1;
                   9116:         }
                   9117:     }
                   9118:     if ($ok_response) {
1.521     raeburn  9119:         return 'ok';
1.772     raeburn  9120:     } else {
                   9121:         return $response;
1.521     raeburn  9122:     }
                   9123: }
                   9124: 
1.792     raeburn  9125: sub auto_instcode_defaults {
                   9126:     my ($domain,$returnhash,$code_order) = @_;
                   9127:     my @homeservers;
1.841     albertel 9128: 
                   9129:     my %servers = &get_servers($domain,'library');
                   9130:     foreach my $tryserver (keys(%servers)) {
                   9131: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9132: 	    push(@homeservers,$tryserver);
                   9133: 	}
1.792     raeburn  9134:     }
1.841     albertel 9135: 
1.792     raeburn  9136:     my $response;
1.841     albertel 9137:     foreach my $server (@homeservers) {
1.792     raeburn  9138:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9139:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9140: 	
                   9141: 	foreach my $pair (split(/\&/,$response)) {
                   9142: 	    my ($name,$value)=split(/\=/,$pair);
                   9143: 	    if ($name eq 'code_order') {
                   9144: 		@{$code_order} = split(/\&/,&unescape($value));
                   9145: 	    } else {
                   9146: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9147: 	    }
                   9148: 	}
                   9149: 	return 'ok';
1.792     raeburn  9150:     }
1.841     albertel 9151: 
                   9152:     return $response;
1.1003    raeburn  9153: }
                   9154: 
                   9155: sub auto_possible_instcodes {
1.1007    raeburn  9156:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9157:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9158:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9159:         return;
                   9160:     }
1.1003    raeburn  9161:     my (@homeservers,$uhome);
                   9162:     if (defined(&domain($domain,'primary'))) {
                   9163:         $uhome=&domain($domain,'primary');
                   9164:         push(@homeservers,&domain($domain,'primary'));
                   9165:     } else {
                   9166:         my %servers = &get_servers($domain,'library');
                   9167:         foreach my $tryserver (keys(%servers)) {
                   9168:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9169:                 push(@homeservers,$tryserver);
                   9170:             }
                   9171:         }
                   9172:     }
                   9173:     my $response;
                   9174:     foreach my $server (@homeservers) {
                   9175:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9176:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9177:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9178:             split(':',$response);
                   9179:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9180:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9181:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9182:             my ($name,$value)=split('=',$item);
                   9183:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9184:         }
                   9185:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9186:             my ($name,$value)=split('=',$item);
                   9187:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9188:         }
                   9189:         return 'ok';
                   9190:     }
                   9191:     return $response;
                   9192: }
1.792     raeburn  9193: 
1.1010    raeburn  9194: sub auto_courserequest_checks {
                   9195:     my ($dom) = @_;
1.1020    raeburn  9196:     my ($homeserver,%validations);
                   9197:     if ($dom =~ /^$match_domain$/) {
                   9198:         $homeserver = &domain($dom,'primary');
                   9199:     }
                   9200:     unless ($homeserver eq 'no_host') {
                   9201:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9202:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9203:             my @items = split(/&/,$response);
                   9204:             foreach my $item (@items) {
                   9205:                 my ($key,$value) = split('=',$item);
                   9206:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9207:             }
                   9208:         }
                   9209:     }
1.1010    raeburn  9210:     return %validations; 
                   9211: }
                   9212: 
1.1020    raeburn  9213: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9214:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9215:     my ($homeserver,$response);
                   9216:     if ($dom =~ /^$match_domain$/) {
                   9217:         $homeserver = &domain($dom,'primary');
                   9218:     }
1.1172.2.43  raeburn  9219:     unless ($homeserver eq 'no_host') {
                   9220:         my $customdata;
                   9221:         if (ref($custominfo) eq 'HASH') {
                   9222:             $customdata = &freeze_escape($custominfo);
                   9223:         }
1.1020    raeburn  9224:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9225:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9226:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9227:                                     $customdata,$homeserver));
1.1020    raeburn  9228:     }
                   9229:     return $response;
                   9230: }
                   9231: 
1.777     albertel 9232: sub auto_validate_class_sec {
1.918     raeburn  9233:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9234:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9235:     my $ownerlist;
                   9236:     if (ref($owners) eq 'ARRAY') {
                   9237:         $ownerlist = join(',',@{$owners});
                   9238:     } else {
                   9239:         $ownerlist = $owners;
                   9240:     }
1.773     raeburn  9241:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9242:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9243:     return $response;
                   9244: }
                   9245: 
1.1172.2.94  raeburn  9246: sub auto_validate_instclasses {
                   9247:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9248:     my ($homeserver,%validations);
                   9249:     $homeserver = &homeserver($cnum,$cdom);
                   9250:     unless ($homeserver eq 'no_host') {
                   9251:         my $ownerlist;
                   9252:         if (ref($owners) eq 'ARRAY') {
                   9253:             $ownerlist = join(',',@{$owners});
                   9254:         } else {
                   9255:             $ownerlist = $owners;
                   9256:         }
                   9257:         if (ref($classesref) eq 'HASH') {
                   9258:             my $classes = &freeze_escape($classesref);
                   9259:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9260:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9261:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9262:                 my @items = split(/&/,$response);
                   9263:                 foreach my $item (@items) {
                   9264:                     my ($key,$value) = split('=',$item);
                   9265:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9266:                 }
                   9267:             }
                   9268:         }
                   9269:     }
                   9270:     return %validations;
                   9271: }
                   9272: 
1.1172.2.38  raeburn  9273: sub auto_crsreq_update {
                   9274:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9275:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9276:     my ($homeserver,%crsreqresponse);
                   9277:     if ($cdom =~ /^$match_domain$/) {
                   9278:         $homeserver = &domain($cdom,'primary');
                   9279:     }
                   9280:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9281:         my $info;
                   9282:         if (ref($inbound) eq 'HASH') {
                   9283:             $info = &freeze_escape($inbound);
                   9284:         }
                   9285:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9286:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9287:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9288:                             &escape($title).':'.&escape($code).':'.
                   9289:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9290:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9291:             my @items = split(/&/,$response);
                   9292:             foreach my $item (@items) {
                   9293:                 my ($key,$value) = split('=',$item);
                   9294:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9295:             }
                   9296:         }
                   9297:     }
                   9298:     return \%crsreqresponse;
                   9299: }
                   9300: 
1.1172.2.78  raeburn  9301: sub auto_export_grades {
                   9302:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9303:     my ($homeserver,%exportresponse);
                   9304:     if ($cdom =~ /^$match_domain$/) {
                   9305:         $homeserver = &domain($cdom,'primary');
                   9306:     }
                   9307:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9308:         my $info;
                   9309:         if (ref($inforef) eq 'HASH') {
                   9310:             $info = &freeze_escape($inforef);
                   9311:         }
                   9312:         if (ref($gradesref) eq 'HASH') {
                   9313:             my $grades = &freeze_escape($gradesref);
                   9314:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9315:                                 $info.':'.$grades,$homeserver);
                   9316:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9317:                 my @items = split(/&/,$response);
                   9318:                 foreach my $item (@items) {
                   9319:                     my ($key,$value) = split('=',$item);
                   9320:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9321:                 }
                   9322:             }
                   9323:         }
                   9324:     }
                   9325:     return \%exportresponse;
                   9326: }
                   9327: 
1.1172.2.68  raeburn  9328: sub check_instcode_cloning {
                   9329:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9330:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9331:         return;
                   9332:     }
                   9333:     my $canclone;
                   9334:     if (@{$code_order} > 0) {
                   9335:         my $instcoderegexp ='^';
                   9336:         my @clonecodes = split(/\&/,$cloner);
                   9337:         foreach my $item (@{$code_order}) {
                   9338:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9339:                 foreach my $pair (@clonecodes) {
                   9340:                     my ($key,$val) = split(/\=/,$pair,2);
                   9341:                     $val = &unescape($val);
                   9342:                     if ($key eq $item) {
                   9343:                         $instcoderegexp .= '('.$val.')';
                   9344:                         last;
                   9345:                     }
                   9346:                 }
                   9347:             } else {
                   9348:                 $instcoderegexp .= $codedefaults->{$item};
                   9349:             }
                   9350:         }
                   9351:         $instcoderegexp .= '$';
                   9352:         my (@from,@to);
                   9353:         eval {
                   9354:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9355:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9356:         };
                   9357:         if ((@from > 0) && (@to > 0)) {
                   9358:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9359:             if (!@diffs) {
                   9360:                 $canclone = 1;
                   9361:             }
                   9362:         }
                   9363:     }
                   9364:     return $canclone;
                   9365: }
                   9366: 
                   9367: sub default_instcode_cloning {
                   9368:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9369:     my (%codedefaults,@code_order,$canclone);
                   9370:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9371:         %codedefaults = %{$codedefaultsref};
                   9372:         @code_order = @{$codeorderref};
                   9373:     } elsif ($clonedom) {
                   9374:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9375:     }
                   9376:     if (($domdefclone) && (@code_order)) {
                   9377:         my @clonecodes = split(/\+/,$domdefclone);
                   9378:         my $instcoderegexp ='^';
                   9379:         foreach my $item (@code_order) {
                   9380:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9381:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9382:             } else {
                   9383:                 $instcoderegexp .= $codedefaults{$item};
                   9384:             }
                   9385:         }
                   9386:         $instcoderegexp .= '$';
                   9387:         my (@from,@to);
                   9388:         eval {
                   9389:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9390:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9391:         };
                   9392:         if ((@from > 0) && (@to > 0)) {
                   9393:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9394:             if (!@diffs) {
                   9395:                 $canclone = 1;
                   9396:             }
                   9397:         }
                   9398:     }
                   9399:     return $canclone;
                   9400: }
                   9401: 
1.679     raeburn  9402: # ------------------------------------------------------- Course Group routines
                   9403: 
                   9404: sub get_coursegroups {
1.809     raeburn  9405:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9406:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9407: }
                   9408: 
1.679     raeburn  9409: sub modify_coursegroup {
                   9410:     my ($cdom,$cnum,$groupsettings) = @_;
                   9411:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9412: }
                   9413: 
1.809     raeburn  9414: sub toggle_coursegroup_status {
                   9415:     my ($cdom,$cnum,$group,$action) = @_;
                   9416:     my ($from_namespace,$to_namespace);
                   9417:     if ($action eq 'delete') {
                   9418:         $from_namespace = 'coursegroups';
                   9419:         $to_namespace = 'deleted_groups';
                   9420:     } else {
                   9421:         $from_namespace = 'deleted_groups';
                   9422:         $to_namespace = 'coursegroups';
                   9423:     }
                   9424:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9425:     if (my $tmp = &error(%curr_group)) {
                   9426:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9427:         return ('read error',$tmp);
                   9428:     } else {
                   9429:         my %savedsettings = %curr_group; 
1.809     raeburn  9430:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9431:         my $deloutcome;
                   9432:         if ($result eq 'ok') {
1.809     raeburn  9433:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9434:         } else {
                   9435:             return ('write error',$result);
                   9436:         }
                   9437:         if ($deloutcome eq 'ok') {
                   9438:             return 'ok';
                   9439:         } else {
                   9440:             return ('delete error',$deloutcome);
                   9441:         }
                   9442:     }
                   9443: }
                   9444: 
1.679     raeburn  9445: sub modify_group_roles {
1.957     raeburn  9446:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9447:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9448:     my $role = 'gr/'.&escape($userprivs);
                   9449:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9450:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9451:     if ($result eq 'ok') {
                   9452:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9453:     }
1.679     raeburn  9454:     return $result;
                   9455: }
                   9456: 
                   9457: sub modify_coursegroup_membership {
                   9458:     my ($cdom,$cnum,$membership) = @_;
                   9459:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9460:     return $result;
                   9461: }
                   9462: 
1.682     raeburn  9463: sub get_active_groups {
                   9464:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9465:     my $now = time;
                   9466:     my %groups = ();
                   9467:     foreach my $key (keys(%env)) {
1.811     albertel 9468:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9469:             my ($start,$end) = split(/\./,$env{$key});
                   9470:             if (($end!=0) && ($end<$now)) { next; }
                   9471:             if (($start!=0) && ($start>$now)) { next; }
                   9472:             if ($1 eq $cdom && $2 eq $cnum) {
                   9473:                 $groups{$3} = $env{$key} ;
                   9474:             }
                   9475:         }
                   9476:     }
                   9477:     return %groups;
                   9478: }
                   9479: 
1.683     raeburn  9480: sub get_group_membership {
                   9481:     my ($cdom,$cnum,$group) = @_;
                   9482:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9483: }
                   9484: 
                   9485: sub get_users_groups {
                   9486:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9487:     my @usersgroups;
1.683     raeburn  9488:     my $cachetime=1800;
                   9489: 
                   9490:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9491:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9492:     if (defined($cached)) {
1.734     albertel 9493:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9494:     } else {  
                   9495:         $grouplist = '';
1.816     raeburn  9496:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9497:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9498:         my $access_end = $env{'course.'.$courseid.
                   9499:                               '.default_enrollment_end_date'};
                   9500:         my $now = time;
                   9501:         foreach my $key (keys(%roleshash)) {
                   9502:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9503:                 my $group = $1;
                   9504:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9505:                     my $start = $2;
                   9506:                     my $end = $1;
                   9507:                     if ($start == -1) { next; } # deleted from group
                   9508:                     if (($start!=0) && ($start>$now)) { next; }
                   9509:                     if (($end!=0) && ($end<$now)) {
                   9510:                         if ($access_end && $access_end < $now) {
                   9511:                             if ($access_end - $end < 86400) {
                   9512:                                 push(@usersgroups,$group);
1.733     raeburn  9513:                             }
                   9514:                         }
1.817     raeburn  9515:                         next;
1.733     raeburn  9516:                     }
1.817     raeburn  9517:                     push(@usersgroups,$group);
1.683     raeburn  9518:                 }
                   9519:             }
                   9520:         }
1.817     raeburn  9521:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9522:         $grouplist = join(':',@usersgroups);
                   9523:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9524:     }
1.733     raeburn  9525:     return @usersgroups;
1.683     raeburn  9526: }
                   9527: 
                   9528: sub devalidate_getgroups_cache {
                   9529:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9530:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9531: 
1.683     raeburn  9532:     my $hashid="$udom:$uname:$courseid";
                   9533:     &devalidate_cache_new('getgroups',$hashid);
                   9534: }
                   9535: 
1.12      www      9536: # ------------------------------------------------------------------ Plain Text
                   9537: 
                   9538: sub plaintext {
1.988     raeburn  9539:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9540:     if ($short =~ m{^cr/}) {
1.758     albertel 9541: 	return (split('/',$short))[-1];
                   9542:     }
1.742     raeburn  9543:     if (!defined($cid)) {
                   9544:         $cid = $env{'request.course.id'};
                   9545:     }
                   9546:     my %rolenames = (
1.1008    raeburn  9547:                       Course    => 'std',
                   9548:                       Community => 'alt1',
1.742     raeburn  9549:                     );
1.1037    raeburn  9550:     if ($cid ne '') {
                   9551:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9552:             unless ($forcedefault) {
                   9553:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9554:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9555:                 return &Apache::lonlocal::mt($roletext);
                   9556:             }
                   9557:         }
                   9558:     }
                   9559:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9560:         (defined($rolenames{$type})) && 
                   9561:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9562:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9563:     } elsif ($cid ne '') {
                   9564:         my $crstype = $env{'course.'.$cid.'.type'};
                   9565:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9566:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9567:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9568:         }
1.742     raeburn  9569:     }
1.1037    raeburn  9570:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9571: }
                   9572: 
                   9573: # ----------------------------------------------------------------- Assign Role
                   9574: 
                   9575: sub assignrole {
1.957     raeburn  9576:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9577:         $context)=@_;
1.21      www      9578:     my $mrole;
                   9579:     if ($role =~ /^cr\//) {
1.393     www      9580:         my $cwosec=$url;
1.811     albertel 9581:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9582: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9583:            my $refused = 1;
                   9584:            if ($context eq 'requestcourses') {
                   9585:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9586:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9587:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9588:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9589:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9590:                            if ($crsenv{'internal.courseowner'} eq
                   9591:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9592:                                $refused = '';
                   9593:                            }
                   9594:                        }
                   9595:                    }
                   9596:                }
                   9597:            }
                   9598:            if ($refused) {
                   9599:                &logthis('Refused custom assignrole: '.
                   9600:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9601:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9602:                return 'refused';
                   9603:            }
1.104     www      9604:         }
1.21      www      9605:         $mrole='cr';
1.678     raeburn  9606:     } elsif ($role =~ /^gr\//) {
                   9607:         my $cwogrp=$url;
1.811     albertel 9608:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9609:         unless (&allowed('mdg',$cwogrp)) {
                   9610:             &logthis('Refused group assignrole: '.
                   9611:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9612:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9613:             return 'refused';
                   9614:         }
                   9615:         $mrole='gr';
1.21      www      9616:     } else {
1.82      www      9617:         my $cwosec=$url;
1.811     albertel 9618:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9619:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9620:             my $refused;
                   9621:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9622:                 if (!(&allowed('c'.$role,$url))) {
                   9623:                     $refused = 1;
                   9624:                 }
                   9625:             } else {
                   9626:                 $refused = 1;
                   9627:             }
1.947     raeburn  9628:             if ($refused) {
1.1045    raeburn  9629:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9630:                 if (!$selfenroll && $context eq 'course') {
                   9631:                     my %crsenv;
                   9632:                     if ($role eq 'cc' || $role eq 'co') {
                   9633:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9634:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9635:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9636:                                 if ($crsenv{'internal.courseowner'} eq 
                   9637:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9638:                                     $refused = '';
                   9639:                                 }
                   9640:                             }
                   9641:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9642:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9643:                                 if ($crsenv{'internal.courseowner'} eq 
                   9644:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9645:                                     $refused = '';
                   9646:                                 }
                   9647:                             }
                   9648:                         }
                   9649:                     }
                   9650:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9651:                     $refused = '';
1.1017    raeburn  9652:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9653:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9654:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9655:                         my $wrongcc;
                   9656:                         if ($cnum =~ /^$match_community$/) {
                   9657:                             $wrongcc = 1 if ($role eq 'cc');
                   9658:                         } else {
                   9659:                             $wrongcc = 1 if ($role eq 'co');
                   9660:                         }
                   9661:                         unless ($wrongcc) {
                   9662:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9663:                             if ($crsenv{'internal.courseowner'} eq 
                   9664:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9665:                                 $refused = '';
                   9666:                             }
1.1017    raeburn  9667:                         }
                   9668:                     }
1.1172.2.9  raeburn  9669:                 } elsif ($context eq 'requestauthor') {
                   9670:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9671:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9672:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9673:                             $refused = '';
                   9674:                         } else {
                   9675:                             my %domdefaults = &get_domain_defaults($udom);
                   9676:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9677:                                 my $checkbystatus;
                   9678:                                 if ($env{'user.adv'}) {
                   9679:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9680:                                     if ($disposition eq 'automatic') {
                   9681:                                         $refused = '';
                   9682:                                     } elsif ($disposition eq '') {
                   9683:                                         $checkbystatus = 1;
                   9684:                                     }
                   9685:                                 } else {
                   9686:                                     $checkbystatus = 1;
                   9687:                                 }
                   9688:                                 if ($checkbystatus) {
                   9689:                                     if ($env{'environment.inststatus'}) {
                   9690:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9691:                                         foreach my $type (@inststatuses) {
                   9692:                                             if (($type ne '') &&
                   9693:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9694:                                                 $refused = '';
                   9695:                                             }
                   9696:                                         }
                   9697:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9698:                                         $refused = '';
                   9699:                                     }
                   9700:                                 }
                   9701:                             }
                   9702:                         }
                   9703:                     }
1.1017    raeburn  9704:                 }
                   9705:                 if ($refused) {
1.947     raeburn  9706:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9707:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9708: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9709:                     return 'refused';
                   9710:                 }
1.932     raeburn  9711:             }
1.1131    raeburn  9712:         } elsif ($role eq 'au') {
                   9713:             if ($url ne '/'.$udom.'/') {
                   9714:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9715:                          ' to assign author role for '.$uname.':'.$udom.
                   9716:                          ' in domain: '.$url.' refused (wrong domain).');
                   9717:                 return 'refused';
                   9718:             }
1.104     www      9719:         }
1.21      www      9720:         $mrole=$role;
                   9721:     }
1.620     albertel 9722:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9723:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9724:     if ($end) { $command.='_'.$end; }
1.21      www      9725:     if ($start) {
                   9726: 	if ($end) { 
1.81      www      9727:            $command.='_'.$start; 
1.21      www      9728:         } else {
1.81      www      9729:            $command.='_0_'.$start;
1.21      www      9730:         }
                   9731:     }
1.739     raeburn  9732:     my $origstart = $start;
                   9733:     my $origend = $end;
1.957     raeburn  9734:     my $delflag;
1.357     www      9735: # actually delete
                   9736:     if ($deleteflag) {
1.373     www      9737: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9738: # modify command to delete the role
1.620     albertel 9739:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9740:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9741: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9742: # set start and finish to negative values for userrolelog
                   9743:            $start=-1;
                   9744:            $end=-1;
1.957     raeburn  9745:            $delflag = 1;
1.357     www      9746:         }
                   9747:     }
                   9748: # send command
1.349     www      9749:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9750: # log new user role if status is ok
1.349     www      9751:     if ($answer eq 'ok') {
1.663     raeburn  9752: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9753:         if (($role eq 'cc') || ($role eq 'in') ||
                   9754:             ($role eq 'ep') || ($role eq 'ad') ||
                   9755:             ($role eq 'ta') || ($role eq 'st') ||
                   9756:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9757:             ($role eq 'co')) {
1.1172.2.13  raeburn  9758: # for course roles, perform group memberships changes triggered by role change.
                   9759:             unless ($role =~ /^gr/) {
                   9760:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9761:                                                  $origstart,$selfenroll,$context);
                   9762:             }
1.1172.2.9  raeburn  9763:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9764:                            $selfenroll,$context);
                   9765:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9766:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9767:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9768:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9769:                            $context);
                   9770:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9771:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9772:                              $context);
                   9773:         }
1.1053    raeburn  9774:         if ($role eq 'cc') {
                   9775:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9776:         }
1.349     www      9777:     }
                   9778:     return $answer;
1.169     harris41 9779: }
                   9780: 
1.1053    raeburn  9781: sub autoupdate_coowners {
                   9782:     my ($url,$end,$start,$uname,$udom) = @_;
                   9783:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9784:     if (($cdom ne '') && ($cnum ne '')) {
                   9785:         my $now = time;
                   9786:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9787:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9788:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9789:             my $instcode = $coursehash{'internal.coursecode'};
                   9790:             if ($instcode ne '') {
1.1056    raeburn  9791:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9792:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9793:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9794:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9795:                         if ($result eq 'valid') {
                   9796:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9797:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9798:                                     push(@newcoowners,$coowner);
                   9799:                                 }
                   9800:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9801:                                     push(@newcoowners,$uname.':'.$udom);
                   9802:                                 }
                   9803:                                 @newcoowners = sort(@newcoowners);
                   9804:                             } else {
                   9805:                                 push(@newcoowners,$uname.':'.$udom);
                   9806:                             }
                   9807:                         } else {
                   9808:                             if ($coursehash{'internal.co-owners'}) {
                   9809:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9810:                                     unless ($coowner eq $uname.':'.$udom) {
                   9811:                                         push(@newcoowners,$coowner);
                   9812:                                     }
                   9813:                                 }
                   9814:                                 unless (@newcoowners > 0) {
                   9815:                                     $delcoowners = 1;
                   9816:                                     $coowners = '';
                   9817:                                 }
                   9818:                             }
                   9819:                         }
                   9820:                         if (@newcoowners || $delcoowners) {
                   9821:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9822:                                             $delcoowners,@newcoowners);
                   9823:                         }
                   9824:                     }
                   9825:                 }
                   9826:             }
                   9827:         }
                   9828:     }
                   9829: }
                   9830: 
                   9831: sub store_coowners {
                   9832:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9833:     my $cid = $cdom.'_'.$cnum;
                   9834:     my ($coowners,$delresult,$putresult);
                   9835:     if (@newcoowners) {
                   9836:         $coowners = join(',',@newcoowners);
                   9837:         my %coownershash = (
                   9838:                             'internal.co-owners' => $coowners,
                   9839:                            );
                   9840:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9841:         if ($putresult eq 'ok') {
                   9842:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9843:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9844:             }
                   9845:         }
                   9846:     }
                   9847:     if ($delcoowners) {
                   9848:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9849:         if ($delresult eq 'ok') {
                   9850:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9851:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9852:             }
                   9853:         }
                   9854:     }
                   9855:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9856:         my %crsinfo =
                   9857:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9858:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9859:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9860:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9861:         }
                   9862:     }
                   9863: }
                   9864: 
1.169     harris41 9865: # -------------------------------------------------- Modify user authentication
1.197     www      9866: # Overrides without validation
                   9867: 
1.169     harris41 9868: sub modifyuserauth {
                   9869:     my ($udom,$uname,$umode,$upass)=@_;
                   9870:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9871:     my $allowed;
                   9872:     if (&allowed('mau',$udom)) {
                   9873:         $allowed = 1;
                   9874:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9875:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9876:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9877:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9878:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9879:         if (($cdom ne '') && ($cnum ne '')) {
                   9880:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9881:             if ($is_owner) {
                   9882:                 $allowed = 1;
                   9883:             }
                   9884:         }
                   9885:     }
                   9886:     unless ($allowed) { return 'refused'; }
1.197     www      9887:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9888:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9889:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9890:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9891: 		     &escape($upass),$uhome);
1.620     albertel 9892:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9893:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9894:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9895:     &log($udom,,$uname,$uhome,
1.620     albertel 9896:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9897:                                      $env{'user.name'}.', '.$umode.
1.197     www      9898:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9899:     unless ($reply eq 'ok') {
1.197     www      9900:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9901: 	return 'error: '.$reply;
                   9902:     }   
1.170     harris41 9903:     return 'ok';
1.80      www      9904: }
                   9905: 
1.81      www      9906: # --------------------------------------------------------------- Modify a user
1.80      www      9907: 
1.81      www      9908: sub modifyuser {
1.206     matthew  9909:     my ($udom,    $uname, $uid,
                   9910:         $umode,   $upass, $first,
                   9911:         $middle,  $last,  $gene,
1.1058    raeburn  9912:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9913:     $udom= &LONCAPA::clean_domain($udom);
                   9914:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9915:     my $showcandelete = 'none';
                   9916:     if (ref($candelete) eq 'ARRAY') {
                   9917:         if (@{$candelete} > 0) {
                   9918:             $showcandelete = join(', ',@{$candelete});
                   9919:         }
                   9920:     }
1.81      www      9921:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9922:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9923: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9924:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9925:                                      ' desiredhome not specified'). 
1.620     albertel 9926:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9927:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9928:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9929:     my $newuser;
                   9930:     if ($uhome eq 'no_host') {
                   9931:         $newuser = 1;
                   9932:     }
1.80      www      9933: # ----------------------------------------------------------------- Create User
1.406     albertel 9934:     if (($uhome eq 'no_host') && 
                   9935: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9936:         my $unhome='';
1.844     albertel 9937:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9938:             $unhome = $desiredhome;
1.620     albertel 9939: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9940: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9941:         } else { # load balancing routine for determining $unhome
1.81      www      9942:             my $loadm=10000000;
1.841     albertel 9943: 	    my %servers = &get_servers($udom,'library');
                   9944: 	    foreach my $tryserver (keys(%servers)) {
                   9945: 		my $answer=reply('load',$tryserver);
                   9946: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9947: 		    $loadm=$answer;
                   9948: 		    $unhome=$tryserver;
                   9949: 		}
1.80      www      9950: 	    }
                   9951:         }
                   9952:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9953: 	    return 'error: unable to find a home server for '.$uname.
                   9954:                    ' in domain '.$udom;
1.80      www      9955:         }
                   9956:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9957:                          &escape($upass),$unhome);
                   9958: 	unless ($reply eq 'ok') {
                   9959:             return 'error: '.$reply;
                   9960:         }   
1.230     stredwic 9961:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9962:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9963: 	    return 'error: unable verify users home machine.';
1.80      www      9964:         }
1.209     matthew  9965:     }   # End of creation of new user
1.80      www      9966: # ---------------------------------------------------------------------- Add ID
                   9967:     if ($uid) {
                   9968:        $uid=~tr/A-Z/a-z/;
                   9969:        my %uidhash=&idrget($udom,$uname);
1.196     www      9970:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9971:          && (!$forceid)) {
1.80      www      9972: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9973: 	      return 'error: user id "'.$uid.'" does not match '.
                   9974:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9975:           }
                   9976:        } else {
                   9977: 	  &idput($udom,($uname => $uid));
                   9978:        }
                   9979:     }
                   9980: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9981:     my @tmp=&get('environment',
1.899     raeburn  9982: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9983:                     'permanentemail','inststatus'],
1.134     albertel 9984: 		   $udom,$uname);
1.1075    raeburn  9985:     my (%names,%oldnames);
1.313     matthew  9986:     if ($tmp[0] =~ m/^error:.*/) { 
                   9987:         %names=(); 
                   9988:     } else {
                   9989:         %names = @tmp;
1.1075    raeburn  9990:         %oldnames = %names;
1.313     matthew  9991:     }
1.388     www      9992: #
1.1058    raeburn  9993: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9994: # of users did not contain them), do not overwrite existing values
                   9995: # unless field is in $candelete array ref.  
                   9996: #
                   9997: 
                   9998:     my @fields = ('firstname','middlename','lastname','generation',
                   9999:                   'permanentemail','id');
                   10000:     my %newvalues;
                   10001:     if (ref($candelete) eq 'ARRAY') {
                   10002:         foreach my $field (@fields) {
                   10003:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10004:                 if ($field eq 'firstname') {
                   10005:                     $names{$field} = $first;
                   10006:                 } elsif ($field eq 'middlename') {
                   10007:                     $names{$field} = $middle;
                   10008:                 } elsif ($field eq 'lastname') {
                   10009:                     $names{$field} = $last;
                   10010:                 } elsif ($field eq 'generation') { 
                   10011:                     $names{$field} = $gene;
                   10012:                 } elsif ($field eq 'permanentemail') {
                   10013:                     $names{$field} = $email;
                   10014:                 } elsif ($field eq 'id') {
                   10015:                     $names{$field}  = $uid;
                   10016:                 }
                   10017:             }
                   10018:         }
                   10019:     }
1.388     www      10020:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10021:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10022:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10023:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10024:     if ($email) {
                   10025:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10026:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10027:     }
1.899     raeburn  10028:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10029:     if (defined($inststatus)) {
                   10030:         $names{'inststatus'} = '';
                   10031:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10032:         if (ref($usertypes) eq 'HASH') {
                   10033:             my @okstatuses; 
                   10034:             foreach my $item (split(/:/,$inststatus)) {
                   10035:                 if (defined($usertypes->{$item})) {
                   10036:                     push(@okstatuses,$item);  
                   10037:                 }
                   10038:             }
                   10039:             if (@okstatuses) {
                   10040:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10041:             }
                   10042:         }
                   10043:     }
1.1075    raeburn  10044:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10045:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10046:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10047:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10048:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10049:     } else {
                   10050:         $logmsg .= ' during self creation';
                   10051:     }
1.1075    raeburn  10052:     my $changed;
                   10053:     if ($newuser) {
                   10054:         $changed = 1;
                   10055:     } else {
                   10056:         foreach my $field (@fields) {
                   10057:             if ($names{$field} ne $oldnames{$field}) {
                   10058:                 $changed = 1;
                   10059:                 last;
                   10060:             }
                   10061:         }
                   10062:     }
                   10063:     unless ($changed) {
                   10064:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10065:         &logthis($logmsg);
                   10066:         return 'ok';
                   10067:     }
                   10068:     my $reply = &put('environment', \%names, $udom,$uname);
                   10069:     if ($reply ne 'ok') { 
                   10070:         return 'error: '.$reply;
                   10071:     }
1.1087    raeburn  10072:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10073:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10074:     }
1.1075    raeburn  10075:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10076:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10077:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10078:     &logthis($logmsg);
1.134     albertel 10079:     return 'ok';
1.80      www      10080: }
                   10081: 
1.81      www      10082: # -------------------------------------------------------------- Modify student
1.80      www      10083: 
1.81      www      10084: sub modifystudent {
                   10085:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10086:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10087:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10088:     if (!$cid) {
1.620     albertel 10089: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10090: 	    return 'not_in_class';
                   10091: 	}
1.80      www      10092:     }
                   10093: # --------------------------------------------------------------- Make the user
1.81      www      10094:     my $reply=&modifyuser
1.209     matthew  10095: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10096:          $desiredhome,$email,$inststatus);
1.80      www      10097:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10098:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10099:     # student's environment
1.297     matthew  10100:     $uid = undef if (!$forceid);
1.455     albertel 10101:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10102: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10103:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10104:     return $reply;
                   10105: }
                   10106: 
                   10107: sub modify_student_enrollment {
1.1172.2.23  raeburn  10108:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10109:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10110:     my ($cdom,$cnum,$chome);
                   10111:     if (!$cid) {
1.620     albertel 10112: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10113: 	    return 'not_in_class';
                   10114: 	}
1.620     albertel 10115: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10116: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10117:     } else {
                   10118: 	($cdom,$cnum)=split(/_/,$cid);
                   10119:     }
1.620     albertel 10120:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10121:     if (!$chome) {
1.457     raeburn  10122: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10123:     }
1.455     albertel 10124:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10125:     # Make sure the user exists
1.81      www      10126:     my $uhome=&homeserver($uname,$udom);
                   10127:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10128: 	return 'error: no such user';
                   10129:     }
1.297     matthew  10130:     # Get student data if we were not given enough information
                   10131:     if (!defined($first)  || $first  eq '' || 
                   10132:         !defined($last)   || $last   eq '' || 
                   10133:         !defined($uid)    || $uid    eq '' || 
                   10134:         !defined($middle) || $middle eq '' || 
                   10135:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10136:         # They did not supply us with enough data to enroll the student, so
                   10137:         # we need to pick up more information.
1.297     matthew  10138:         my %tmp = &get('environment',
1.294     matthew  10139:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10140:                        ,$udom,$uname);
                   10141: 
1.800     albertel 10142:         #foreach my $key (keys(%tmp)) {
                   10143:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10144:         #}
1.294     matthew  10145:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10146:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10147:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10148:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10149:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10150:     }
1.556     albertel 10151:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10152:     my $user = "$uname:$udom";
                   10153:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10154:     my $reply=cput('classlist',
1.1148    raeburn  10155: 		   {$user => 
1.1172.2.76  raeburn  10156: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10157: 		   $cdom,$cnum);
1.1148    raeburn  10158:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10159:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10160:     } else { 
1.81      www      10161: 	return 'error: '.$reply;
                   10162:     }
1.297     matthew  10163:     # Add student role to user
1.83      www      10164:     my $uurl='/'.$cid;
1.81      www      10165:     $uurl=~s/\_/\//g;
                   10166:     if ($usec) {
                   10167: 	$uurl.='/'.$usec;
                   10168:     }
1.1148    raeburn  10169:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10170:                              $selfenroll,$context);
                   10171:     if ($result ne 'ok') {
                   10172:         if ($old_entry{$user} ne '') {
                   10173:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10174:         } else {
                   10175:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10176:         }
                   10177:     }
                   10178:     return $result; 
1.21      www      10179: }
                   10180: 
1.556     albertel 10181: sub format_name {
                   10182:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10183:     my $name;
                   10184:     if ($first ne 'lastname') {
                   10185: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10186:     } else {
                   10187: 	if ($lastname=~/\S/) {
                   10188: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10189: 	    $name=~s/\s+,/,/;
                   10190: 	} else {
                   10191: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10192: 	}
                   10193:     }
                   10194:     $name=~s/^\s+//;
                   10195:     $name=~s/\s+$//;
                   10196:     $name=~s/\s+/ /g;
                   10197:     return $name;
                   10198: }
                   10199: 
1.84      www      10200: # ------------------------------------------------- Write to course preferences
                   10201: 
                   10202: sub writecoursepref {
                   10203:     my ($courseid,%prefs)=@_;
                   10204:     $courseid=~s/^\///;
                   10205:     $courseid=~s/\_/\//g;
                   10206:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10207:     my $chome=homeserver($cnum,$cdomain);
                   10208:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10209: 	return 'error: no such course';
                   10210:     }
                   10211:     my $cstring='';
1.800     albertel 10212:     foreach my $pref (keys(%prefs)) {
                   10213: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10214:     }
1.84      www      10215:     $cstring=~s/\&$//;
                   10216:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10217: }
                   10218: 
                   10219: # ---------------------------------------------------------- Make/modify course
                   10220: 
                   10221: sub createcourse {
1.741     raeburn  10222:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10223:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10224:     $url=&declutter($url);
                   10225:     my $cid='';
1.1028    raeburn  10226:     if ($context eq 'requestcourses') {
                   10227:         my $can_create = 0;
                   10228:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10229:         if ($udom eq $ownerdom) {
                   10230:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10231:                                   $context)) {
                   10232:                 $can_create = 1;
                   10233:             }
                   10234:         } else {
                   10235:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10236:                                            $category);
                   10237:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10238:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10239:                 if (@curr > 0) {
                   10240:                     my @options = qw(approval validate autolimit);
                   10241:                     my $optregex = join('|',@options);
                   10242:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10243:                         $can_create = 1;
                   10244:                     }
                   10245:                 }
                   10246:             }
                   10247:         }
                   10248:         if ($can_create) {
                   10249:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10250:                 unless (&allowed('ccc',$udom)) {
                   10251:                     return 'refused'; 
                   10252:                 }
1.1017    raeburn  10253:             }
                   10254:         } else {
                   10255:             return 'refused';
                   10256:         }
1.1028    raeburn  10257:     } elsif (!&allowed('ccc',$udom)) {
                   10258:         return 'refused';
1.84      www      10259:     }
1.1011    raeburn  10260: # --------------------------------------------------------------- Get Unique ID
                   10261:     my $uname;
                   10262:     if ($cnum =~ /^$match_courseid$/) {
                   10263:         my $chome=&homeserver($cnum,$udom,'true');
                   10264:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10265:             $uname = $cnum;
                   10266:         } else {
1.1038    raeburn  10267:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10268:         }
                   10269:     } else {
1.1038    raeburn  10270:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10271:     }
                   10272:     return $uname if ($uname =~ /^error/);
                   10273: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10274:     if (!defined($course_server)) {
                   10275:         if (defined(&domain($udom,'primary'))) {
                   10276:             $course_server = &domain($udom,'primary');
                   10277:         } else {
                   10278:             $course_server = $env{'user.home'}; 
                   10279:         }
                   10280:     }
                   10281:     my %host_servers =
                   10282:         &Apache::lonnet::get_servers($udom,'library');
                   10283:     unless ($host_servers{$course_server}) {
                   10284:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10285:     }
1.84      www      10286: # ------------------------------------------------------------- Make the course
                   10287:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10288:                       $course_server);
1.84      www      10289:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10290:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10291:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10292: 	return 'error: no such course';
                   10293:     }
1.271     www      10294: # ----------------------------------------------------------------- Course made
1.516     raeburn  10295: # log existence
1.1029    raeburn  10296:     my $now = time;
1.918     raeburn  10297:     my $newcourse = {
                   10298:                     $udom.'_'.$uname => {
1.921     raeburn  10299:                                      description => $description,
                   10300:                                      inst_code   => $inst_code,
                   10301:                                      owner       => $course_owner,
                   10302:                                      type        => $crstype,
1.1029    raeburn  10303:                                      creator     => $env{'user.name'}.':'.
                   10304:                                                     $env{'user.domain'},
                   10305:                                      created     => $now,
                   10306:                                      context     => $context,
1.918     raeburn  10307:                                                 },
                   10308:                     };
1.921     raeburn  10309:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10310: # set toplevel url
1.271     www      10311:     my $topurl=$url;
                   10312:     unless ($nonstandard) {
                   10313: # ------------------------------------------ For standard courses, make top url
                   10314:         my $mapurl=&clutter($url);
1.278     www      10315:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10316:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10317: <map>
                   10318: <resource id="1" type="start"></resource>
                   10319: <resource id="2" src="$mapurl"></resource>
                   10320: <resource id="3" type="finish"></resource>
                   10321: <link index="1" from="1" to="2"></link>
                   10322: <link index="2" from="2" to="3"></link>
                   10323: </map>
                   10324: ENDINITMAP
                   10325:         $topurl=&declutter(
1.638     albertel 10326:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10327:                           );
                   10328:     }
                   10329: # ----------------------------------------------------------- Write preferences
1.84      www      10330:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10331:                      ('description'              => $description,
                   10332:                       'url'                      => $topurl,
                   10333:                       'internal.creator'         => $env{'user.name'}.':'.
                   10334:                                                     $env{'user.domain'},
                   10335:                       'internal.created'         => $now,
                   10336:                       'internal.creationcontext' => $context)
                   10337:                     );
1.84      www      10338:     return '/'.$udom.'/'.$uname;
                   10339: }
                   10340: 
1.1011    raeburn  10341: # ------------------------------------------------------------------- Create ID
                   10342: sub generate_coursenum {
1.1038    raeburn  10343:     my ($udom,$crstype) = @_;
1.1011    raeburn  10344:     my $domdesc = &domain($udom);
                   10345:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10346:     my $first;
                   10347:     if ($crstype eq 'Community') {
                   10348:         $first = '0';
                   10349:     } else {
                   10350:         $first = int(1+rand(9)); 
                   10351:     } 
                   10352:     my $uname=$first.
1.1011    raeburn  10353:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10354:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10355:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10356: # ----------------------------------------------- Make sure that does not exist
                   10357:     my $uhome=&homeserver($uname,$udom,'true');
                   10358:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10359:         if ($crstype eq 'Community') {
                   10360:             $first = '0';
                   10361:         } else {
                   10362:             $first = int(1+rand(9));
                   10363:         }
                   10364:         $uname=$first.
1.1011    raeburn  10365:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10366:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10367:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10368:         $uhome=&homeserver($uname,$udom,'true');
                   10369:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10370:             return 'error: unable to generate unique course-ID';
                   10371:         }
                   10372:     }
                   10373:     return $uname;
                   10374: }
                   10375: 
1.813     albertel 10376: sub is_course {
1.1167    droeschl 10377:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10378:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10379:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10380:     my $uhome=&homeserver($cnum,$cdom);
                   10381:     my $iscourse;
                   10382:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10383:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10384:     } else {
                   10385:         my $hashid = $cdom.':'.$cnum;
                   10386:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10387:         unless (defined($cached)) {
                   10388:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10389:                                         $cnum,undef,undef,'.');
                   10390:             $iscourse = 0;
                   10391:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10392:                 $iscourse = 1;
                   10393:             }
                   10394:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10395:         }
                   10396:     }
                   10397:     return unless($iscourse);
1.1167    droeschl 10398:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10399: }
                   10400: 
1.1015    raeburn  10401: sub store_userdata {
                   10402:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10403:     my $result;
1.1016    raeburn  10404:     if ($datakey ne '') {
1.1013    raeburn  10405:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10406:             if ($udom eq '' || $uname eq '') {
                   10407:                 $udom = $env{'user.domain'};
                   10408:                 $uname = $env{'user.name'};
                   10409:             }
                   10410:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10411:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10412:                 $result = 'error: no_host';
                   10413:             } else {
                   10414:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10415:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10416: 
                   10417:                 my $namevalue='';
                   10418:                 foreach my $key (keys(%{$storehash})) {
                   10419:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10420:                 }
                   10421:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10422:                 unless ($namespace eq 'courserequests') {
                   10423:                     $datakey = &escape($datakey);
                   10424:                 }
1.1105    raeburn  10425:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10426:                                   $namevalue,$uhome);
1.1013    raeburn  10427:             }
                   10428:         } else {
                   10429:             $result = 'error: data to store was not a hash reference'; 
                   10430:         }
                   10431:     } else {
                   10432:         $result= 'error: invalid requestkey'; 
                   10433:     }
                   10434:     return $result;
                   10435: }
                   10436: 
1.21      www      10437: # ---------------------------------------------------------- Assign Custom Role
                   10438: 
                   10439: sub assigncustomrole {
1.957     raeburn  10440:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10441:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10442:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10443: }
                   10444: 
                   10445: # ----------------------------------------------------------------- Revoke Role
                   10446: 
                   10447: sub revokerole {
1.957     raeburn  10448:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10449:     my $now=time;
1.965     raeburn  10450:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10451: }
                   10452: 
                   10453: # ---------------------------------------------------------- Revoke Custom Role
                   10454: 
                   10455: sub revokecustomrole {
1.957     raeburn  10456:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10457:     my $now=time;
1.357     www      10458:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10459:            $deleteflag,$selfenroll,$context);
1.17      www      10460: }
                   10461: 
1.533     banghart 10462: # ------------------------------------------------------------ Disk usage
1.535     albertel 10463: sub diskusage {
1.955     raeburn  10464:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10465:     $directorypath =~ s/\/$//;
                   10466:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10467:                        .&escape($getpropath).':'.&escape($uname).':'
                   10468:                        .&escape($udom),homeserver($uname,$udom));
                   10469:     if ($listing eq 'unknown_cmd') {
                   10470:         if ($getpropath) {
                   10471:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10472:         }
                   10473:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10474:     }
1.514     albertel 10475:     return $listing;
1.512     banghart 10476: }
                   10477: 
1.566     banghart 10478: sub is_locked {
1.1096    raeburn  10479:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10480:     my @check;
                   10481:     my $is_locked;
1.1093    raeburn  10482:     push (@check,$file_name);
1.613     albertel 10483:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10484: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10485:     my ($tmp)=keys(%locked);
                   10486:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10487:     
1.566     banghart 10488:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10489:         $is_locked = 'false';
                   10490:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10491:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10492:                $is_locked = 'true';
1.1096    raeburn  10493:                if (ref($which) eq 'ARRAY') {
                   10494:                    push(@{$which},$entry);
                   10495:                } else {
                   10496:                    last;
                   10497:                }
1.745     raeburn  10498:            }
                   10499:        }
1.566     banghart 10500:     } else {
                   10501:         $is_locked = 'false';
                   10502:     }
1.1093    raeburn  10503:     return $is_locked;
1.566     banghart 10504: }
                   10505: 
1.759     albertel 10506: sub declutter_portfile {
                   10507:     my ($file) = @_;
1.833     albertel 10508:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10509:     return $file;
                   10510: }
                   10511: 
1.559     banghart 10512: # ------------------------------------------------------------- Mark as Read Only
                   10513: 
                   10514: sub mark_as_readonly {
                   10515:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10516:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10517:     my ($tmp)=keys(%current_permissions);
                   10518:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10519:     foreach my $file (@{$files}) {
1.759     albertel 10520: 	$file = &declutter_portfile($file);
1.561     banghart 10521:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10522:     }
1.613     albertel 10523:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10524:     return;
                   10525: }
                   10526: 
1.572     banghart 10527: # ------------------------------------------------------------Save Selected Files
                   10528: 
                   10529: sub save_selected_files {
                   10530:     my ($user, $path, @files) = @_;
                   10531:     my $filename = $user."savedfiles";
1.573     banghart 10532:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10533:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10534:     foreach my $file (@files) {
1.620     albertel 10535:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10536:     }
                   10537:     foreach my $file (@other_files) {
1.574     banghart 10538:         print (OUT $file."\n");
1.572     banghart 10539:     }
1.574     banghart 10540:     close (OUT);
1.572     banghart 10541:     return 'ok';
                   10542: }
                   10543: 
1.574     banghart 10544: sub clear_selected_files {
                   10545:     my ($user) = @_;
                   10546:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10547:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10548:     print (OUT undef);
                   10549:     close (OUT);
                   10550:     return ("ok");    
                   10551: }
                   10552: 
1.572     banghart 10553: sub files_in_path {
                   10554:     my ($user, $path) = @_;
                   10555:     my $filename = $user."savedfiles";
                   10556:     my %return_files;
1.1172.2.96  raeburn  10557:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10558:     while (my $line_in = <IN>) {
1.574     banghart 10559:         chomp ($line_in);
                   10560:         my @paths_and_file = split (m!/!, $line_in);
                   10561:         my $file_part = pop (@paths_and_file);
                   10562:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10563:         $path_part.='/';
                   10564:         my $path_and_file = $path_part.$file_part;
                   10565:         if ($path_part eq $path) {
                   10566:             $return_files{$file_part}= 'selected';
                   10567:         }
                   10568:     }
1.574     banghart 10569:     close (IN);
                   10570:     return (\%return_files);
1.572     banghart 10571: }
                   10572: 
                   10573: # called in portfolio select mode, to show files selected NOT in current directory
                   10574: sub files_not_in_path {
                   10575:     my ($user, $path) = @_;
                   10576:     my $filename = $user."savedfiles";
                   10577:     my @return_files;
                   10578:     my $path_part;
1.1172.2.96  raeburn  10579:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10580:     while (my $line = <IN>) {
1.572     banghart 10581:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10582:         my @paths_and_file = split(m|/|, $line);
                   10583:         my $file_part = pop(@paths_and_file);
                   10584:         chomp($file_part);
                   10585:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10586:         $path_part .= '/';
                   10587:         my $path_and_file = $path_part.$file_part;
                   10588:         if ($path_part ne $path) {
1.800     albertel 10589:             push(@return_files, ($path_and_file));
1.572     banghart 10590:         }
                   10591:     }
1.800     albertel 10592:     close(OUT);
1.574     banghart 10593:     return (@return_files);
1.572     banghart 10594: }
                   10595: 
1.745     raeburn  10596: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10597: 
1.745     raeburn  10598: sub get_portfile_permissions {
                   10599:     my ($domain,$user) = @_;
1.613     albertel 10600:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10601:     my ($tmp)=keys(%current_permissions);
                   10602:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10603:     return \%current_permissions;
                   10604: }
                   10605: 
                   10606: #---------------------------------------------Get portfolio file access controls
                   10607: 
1.749     raeburn  10608: sub get_access_controls {
1.745     raeburn  10609:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10610:     my %access;
                   10611:     my $real_file = $file;
                   10612:     $file =~ s/\.meta$//;
1.745     raeburn  10613:     if (defined($file)) {
1.749     raeburn  10614:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10615:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10616:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10617:             }
                   10618:         }
1.745     raeburn  10619:     } else {
1.749     raeburn  10620:         foreach my $key (keys(%{$current_permissions})) {
                   10621:             if ($key =~ /\0accesscontrol$/) {
                   10622:                 if (defined($group)) {
                   10623:                     if ($key !~ m-^\Q$group\E/-) {
                   10624:                         next;
                   10625:                     }
                   10626:                 }
                   10627:                 my ($fullpath) = split(/\0/,$key);
                   10628:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10629:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10630:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10631:                     }
                   10632:                 }
                   10633:             }
                   10634:         }
                   10635:     }
                   10636:     return %access;
                   10637: }
                   10638: 
                   10639: sub modify_access_controls {
                   10640:     my ($file_name,$changes,$domain,$user)=@_;
                   10641:     my ($outcome,$deloutcome);
                   10642:     my %store_permissions;
                   10643:     my %new_values;
                   10644:     my %new_control;
                   10645:     my %translation;
                   10646:     my @deletions = ();
                   10647:     my $now = time;
                   10648:     if (exists($$changes{'activate'})) {
                   10649:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10650:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10651:             my $numnew = scalar(@newitems);
                   10652:             for (my $i=0; $i<$numnew; $i++) {
                   10653:                 my $newkey = $newitems[$i];
                   10654:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10655:                 if ($newkey =~ /^\d+:/) { 
                   10656:                     $newkey =~ s/^(\d+)/$newid/;
                   10657:                     $translation{$1} = $newid;
                   10658:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10659:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10660:                     $translation{$1} = $newid;
                   10661:                 }
1.749     raeburn  10662:                 $new_values{$file_name."\0".$newkey} = 
                   10663:                                           $$changes{'activate'}{$newitems[$i]};
                   10664:                 $new_control{$newkey} = $now;
                   10665:             }
                   10666:         }
                   10667:     }
                   10668:     my %todelete;
                   10669:     my %changed_items;
                   10670:     foreach my $action ('delete','update') {
                   10671:         if (exists($$changes{$action})) {
                   10672:             if (ref($$changes{$action}) eq 'HASH') {
                   10673:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10674:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10675:                     if ($action eq 'delete') { 
                   10676:                         $todelete{$itemnum} = 1;
                   10677:                     } else {
                   10678:                         $changed_items{$itemnum} = $key;
                   10679:                     }
                   10680:                 }
1.745     raeburn  10681:             }
                   10682:         }
1.749     raeburn  10683:     }
                   10684:     # get lock on access controls for file.
                   10685:     my $lockhash = {
                   10686:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10687:                                                        ':'.$env{'user.domain'},
                   10688:                    }; 
                   10689:     my $tries = 0;
                   10690:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10691:    
1.1172.2.79  raeburn  10692:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10693:         $tries ++;
1.1172.2.79  raeburn  10694:         sleep(0.1);
1.749     raeburn  10695:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10696:     }
                   10697:     if ($gotlock eq 'ok') {
                   10698:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10699:         my ($tmp)=keys(%curr_permissions);
                   10700:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10701:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10702:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10703:             if (ref($curr_controls) eq 'HASH') {
                   10704:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10705:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10706:                     if (defined($todelete{$itemnum})) {
                   10707:                         push(@deletions,$file_name."\0".$control_item);
                   10708:                     } else {
                   10709:                         if (defined($changed_items{$itemnum})) {
                   10710:                             $new_control{$changed_items{$itemnum}} = $now;
                   10711:                             push(@deletions,$file_name."\0".$control_item);
                   10712:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10713:                         } else {
                   10714:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10715:                         }
                   10716:                     }
1.745     raeburn  10717:                 }
                   10718:             }
                   10719:         }
1.970     raeburn  10720:         my ($group);
                   10721:         if (&is_course($domain,$user)) {
                   10722:             ($group,my $file) = split(/\//,$file_name,2);
                   10723:         }
1.749     raeburn  10724:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10725:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10726:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10727:         #  remove lock
                   10728:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10729:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10730:         my $sqlresult =
1.970     raeburn  10731:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10732:                                     $group);
1.749     raeburn  10733:     } else {
                   10734:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10735:     }
1.749     raeburn  10736:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10737: }
                   10738: 
1.827     raeburn  10739: sub make_public_indefinitely {
                   10740:     my ($requrl) = @_;
                   10741:     my $now = time;
                   10742:     my $action = 'activate';
                   10743:     my $aclnum = 0;
                   10744:     if (&is_portfolio_url($requrl)) {
                   10745:         my (undef,$udom,$unum,$file_name,$group) =
                   10746:             &parse_portfolio_url($requrl);
                   10747:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10748:         my %access_controls = &get_access_controls($current_perms,
                   10749:                                                    $group,$file_name);
                   10750:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10751:             my ($num,$scope,$end,$start) = 
                   10752:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10753:             if ($scope eq 'public') {
                   10754:                 if ($start <= $now && $end == 0) {
                   10755:                     $action = 'none';
                   10756:                 } else {
                   10757:                     $action = 'update';
                   10758:                     $aclnum = $num;
                   10759:                 }
                   10760:                 last;
                   10761:             }
                   10762:         }
                   10763:         if ($action eq 'none') {
                   10764:              return 'ok';
                   10765:         } else {
                   10766:             my %changes;
                   10767:             my $newend = 0;
                   10768:             my $newstart = $now;
                   10769:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10770:             $changes{$action}{$newkey} = {
                   10771:                 type => 'public',
                   10772:                 time => {
                   10773:                     start => $newstart,
                   10774:                     end   => $newend,
                   10775:                 },
                   10776:             };
                   10777:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10778:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10779:             return $outcome;
                   10780:         }
                   10781:     } else {
                   10782:         return 'invalid';
                   10783:     }
                   10784: }
                   10785: 
1.745     raeburn  10786: #------------------------------------------------------Get Marked as Read Only
                   10787: 
                   10788: sub get_marked_as_readonly {
                   10789:     my ($domain,$user,$what,$group) = @_;
                   10790:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10791:     my @readonly_files;
1.629     banghart 10792:     my $cmp1=$what;
                   10793:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10794:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10795:         if (defined($group)) {
                   10796:             if ($file_name !~ m-^\Q$group\E/-) {
                   10797:                 next;
                   10798:             }
                   10799:         }
1.561     banghart 10800:         if (ref($value) eq "ARRAY"){
                   10801:             foreach my $stored_what (@{$value}) {
1.629     banghart 10802:                 my $cmp2=$stored_what;
1.759     albertel 10803:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10804:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10805:                 }
1.629     banghart 10806:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10807:                     push(@readonly_files, $file_name);
1.745     raeburn  10808:                     last;
1.563     banghart 10809:                 } elsif (!defined($what)) {
                   10810:                     push(@readonly_files, $file_name);
1.745     raeburn  10811:                     last;
1.561     banghart 10812:                 }
                   10813:             }
1.745     raeburn  10814:         }
1.561     banghart 10815:     }
                   10816:     return @readonly_files;
                   10817: }
1.577     banghart 10818: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10819: 
1.577     banghart 10820: sub get_marked_as_readonly_hash {
1.745     raeburn  10821:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10822:     my %readonly_files;
1.745     raeburn  10823:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10824:         if (defined($group)) {
                   10825:             if ($file_name !~ m-^\Q$group\E/-) {
                   10826:                 next;
                   10827:             }
                   10828:         }
1.577     banghart 10829:         if (ref($value) eq "ARRAY"){
                   10830:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10831:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10832:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10833:                         if ($lock_descriptor eq 'graded') {
                   10834:                             $readonly_files{$file_name} = 'graded';
                   10835:                         } elsif ($lock_descriptor eq 'handback') {
                   10836:                             $readonly_files{$file_name} = 'handback';
                   10837:                         } else {
                   10838:                             if (!exists($readonly_files{$file_name})) {
                   10839:                                 $readonly_files{$file_name} = 'locked';
                   10840:                             }
                   10841:                         }
1.745     raeburn  10842:                     }
1.750     banghart 10843:                 } 
1.577     banghart 10844:             }
                   10845:         } 
                   10846:     }
                   10847:     return %readonly_files;
                   10848: }
1.559     banghart 10849: # ------------------------------------------------------------ Unmark as Read Only
                   10850: 
                   10851: sub unmark_as_readonly {
1.629     banghart 10852:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10853:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10854:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10855:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10856:     my $symb_crs = $what;
                   10857:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10858:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10859:     my ($tmp)=keys(%current_permissions);
                   10860:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10861:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10862:     foreach my $file (@readonly_files) {
1.759     albertel 10863: 	my $clean_file = &declutter_portfile($file);
                   10864: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10865: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10866:         my @new_locks;
                   10867:         my @del_keys;
                   10868:         if (ref($current_locks) eq "ARRAY"){
                   10869:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10870:                 my $compare=$locker;
1.749     raeburn  10871:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10872:                     $compare=join('',@{$locker});
1.746     raeburn  10873:                     if ($compare ne $symb_crs) {
                   10874:                         push(@new_locks, $locker);
                   10875:                     }
1.563     banghart 10876:                 }
                   10877:             }
1.650     albertel 10878:             if (scalar(@new_locks) > 0) {
1.563     banghart 10879:                 $current_permissions{$file} = \@new_locks;
                   10880:             } else {
                   10881:                 push(@del_keys, $file);
1.613     albertel 10882:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10883:                 delete($current_permissions{$file});
1.563     banghart 10884:             }
                   10885:         }
1.561     banghart 10886:     }
1.613     albertel 10887:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10888:     return;
                   10889: }
1.512     banghart 10890: 
1.17      www      10891: # ------------------------------------------------------------ Directory lister
                   10892: 
                   10893: sub dirlist {
1.955     raeburn  10894:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10895:     $uri=~s/^\///;
                   10896:     $uri=~s/\/$//;
1.253     stredwic 10897:     my ($udom, $uname);
1.955     raeburn  10898:     if ($getuserdir) {
1.253     stredwic 10899:         $udom = $userdomain;
                   10900:         $uname = $username;
1.955     raeburn  10901:     } else {
                   10902:         (undef,$udom,$uname)=split(/\//,$uri);
                   10903:         if(defined($userdomain)) {
                   10904:             $udom = $userdomain;
                   10905:         }
                   10906:         if(defined($username)) {
                   10907:             $uname = $username;
                   10908:         }
1.253     stredwic 10909:     }
1.955     raeburn  10910:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10911: 
1.955     raeburn  10912:     $dirRoot = $perlvar{'lonDocRoot'};
                   10913:     if (defined($getpropath)) {
                   10914:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10915:         $dirRoot =~ s/\/$//;
1.955     raeburn  10916:     } elsif (defined($getuserdir)) {
                   10917:         my $subdir=$uname.'__';
                   10918:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10919:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10920:                    ."/$udom/$subdir/$uname";
                   10921:     } elsif (defined($alternateRoot)) {
                   10922:         $dirRoot = $alternateRoot;
1.751     banghart 10923:     }
1.253     stredwic 10924: 
                   10925:     if($udom) {
                   10926:         if($uname) {
1.1135    raeburn  10927:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10928:             if ($uhome eq 'no_host') {
                   10929:                 return ([],'no_host');
                   10930:             }
1.955     raeburn  10931:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10932:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10933:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10934:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10935:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10936:             } else {
                   10937:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10938:             }
1.605     matthew  10939:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10940:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10941:                 @listing_results = split(/:/,$listing);
                   10942:             } else {
                   10943:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10944:             }
1.1135    raeburn  10945:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10946:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10947:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10948:                 return ([],$listing);
                   10949:             } else {
                   10950:                 return (\@listing_results);
1.1135    raeburn  10951:             }
1.955     raeburn  10952:         } elsif(!$alternateRoot) {
1.1136    raeburn  10953:             my (%allusers,%listerror);
1.841     albertel 10954: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10955:  	    foreach my $tryserver (keys(%servers)) {
                   10956:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10957:                                   &escape($udom),$tryserver);
                   10958:                 if ($listing eq 'unknown_cmd') {
                   10959: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10960: 				      $udom, $tryserver);
                   10961:                 } else {
                   10962:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10963:                 }
1.841     albertel 10964: 		if ($listing eq 'unknown_cmd') {
                   10965: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10966: 				      $udom, $tryserver);
                   10967: 		    @listing_results = split(/:/,$listing);
                   10968: 		} else {
                   10969: 		    @listing_results =
                   10970: 			map { &unescape($_); } split(/:/,$listing);
                   10971: 		}
1.1136    raeburn  10972:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10973:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10974:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10975:                     $listerror{$tryserver} = $listing;
                   10976:                 } else {
1.841     albertel 10977: 		    foreach my $line (@listing_results) {
                   10978: 			my ($entry) = split(/&/,$line,2);
                   10979: 			$allusers{$entry} = 1;
                   10980: 		    }
                   10981: 		}
1.253     stredwic 10982:             }
1.1136    raeburn  10983:             my @alluserslist=();
1.800     albertel 10984:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10985:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10986:             }
1.1172.2.80  raeburn  10987:             if (!%listerror) {
                   10988:                 # no errors
                   10989:                 return (\@alluserslist);
                   10990:             } elsif (scalar(keys(%servers)) == 1) {
                   10991:                 # one library server, one error
                   10992:                 my ($key) = keys(%listerror);
                   10993:                 return (\@alluserslist, $listerror{$key});
                   10994:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10995:                 # con_lost indicates that we might miss data from at least one
                   10996:                 # library server
                   10997:                 return (\@alluserslist, 'con_lost');
                   10998:             } else {
                   10999:                 # multiple library servers and no con_lost -> data should be
                   11000:                 # complete.
                   11001:                 return (\@alluserslist);
                   11002:             }
                   11003: 
1.253     stredwic 11004:         } else {
1.1136    raeburn  11005:             return ([],'missing username');
1.253     stredwic 11006:         }
1.955     raeburn  11007:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11008:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11009:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11010:         return (\@all_domains);
1.955     raeburn  11011:     } else {
1.1136    raeburn  11012:         return ([],'missing domain');
1.275     stredwic 11013:     }
                   11014: }
                   11015: 
                   11016: # --------------------------------------------- GetFileTimestamp
                   11017: # This function utilizes dirlist and returns the date stamp for
                   11018: # when it was last modified.  It will also return an error of -1
                   11019: # if an error occurs
                   11020: 
                   11021: sub GetFileTimestamp {
1.955     raeburn  11022:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11023:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11024:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11025:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11026:                                     undef,$getuserdir);
                   11027:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11028:         return -1;
                   11029:     }
                   11030:     if (ref($fileref) eq 'ARRAY') {
                   11031:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11032:         # @stats contains first the filename, then the stat output
                   11033:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11034:     } else {
                   11035:         return -1;
1.253     stredwic 11036:     }
1.26      www      11037: }
                   11038: 
1.712     albertel 11039: sub stat_file {
                   11040:     my ($uri) = @_;
1.787     albertel 11041:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11042: 
1.955     raeburn  11043:     my ($udom,$uname,$file);
1.712     albertel 11044:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11045: 	($udom,$uname,$file) =
1.811     albertel 11046: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11047: 	$file = 'userfiles/'.$file;
                   11048:     }
                   11049:     if ($uri =~ m-^/res/-) {
                   11050: 	($udom,$uname) = 
1.807     albertel 11051: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11052: 	$file = $uri;
                   11053:     }
                   11054: 
                   11055:     if (!$udom || !$uname || !$file) {
                   11056: 	# unable to handle the uri
                   11057: 	return ();
                   11058:     }
1.956     raeburn  11059:     my $getpropath;
                   11060:     if ($file =~ /^userfiles\//) {
                   11061:         $getpropath = 1;
                   11062:     }
1.1136    raeburn  11063:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11064:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11065:         return ();
                   11066:     } else {
                   11067:         if (ref($listref) eq 'ARRAY') {
                   11068:             my @stats = split('&',$listref->[0]);
                   11069: 	    shift(@stats); #filename is first
                   11070: 	    return @stats;
                   11071:         }
1.712     albertel 11072:     }
                   11073:     return ();
                   11074: }
                   11075: 
1.26      www      11076: # -------------------------------------------------------- Value of a Condition
                   11077: 
1.713     albertel 11078: # gets the value of a specific preevaluated condition
                   11079: #    stored in the string  $env{user.state.<cid>}
                   11080: # or looks up a condition reference in the bighash and if if hasn't
                   11081: # already been evaluated recurses into docondval to get the value of
                   11082: # the condition, then memoizing it to 
                   11083: #   $env{user.state.<cid>.<condition>}
1.40      www      11084: sub directcondval {
                   11085:     my $number=shift;
1.620     albertel 11086:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11087: 	&Apache::lonuserstate::evalstate();
                   11088:     }
1.713     albertel 11089:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11090: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11091:     } elsif ($number =~ /^_/) {
                   11092: 	my $sub_condition;
                   11093: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11094: 		&GDBM_READER(),0640)) {
                   11095: 	    $sub_condition=$bighash{'conditions'.$number};
                   11096: 	    untie(%bighash);
                   11097: 	}
                   11098: 	my $value = &docondval($sub_condition);
1.949     raeburn  11099: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11100: 	return $value;
                   11101:     }
1.620     albertel 11102:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11103:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11104:     } else {
                   11105:        return 2;
                   11106:     }
                   11107: }
                   11108: 
1.713     albertel 11109: # get the collection of conditions for this resource
1.26      www      11110: sub condval {
                   11111:     my $condidx=shift;
1.54      www      11112:     my $allpathcond='';
1.713     albertel 11113:     foreach my $cond (split(/\|/,$condidx)) {
                   11114: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11115: 	    $allpathcond.=
                   11116: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11117: 	}
1.191     harris41 11118:     }
1.54      www      11119:     $allpathcond=~s/\|$//;
1.713     albertel 11120:     return &docondval($allpathcond);
                   11121: }
                   11122: 
                   11123: #evaluates an expression of conditions
                   11124: sub docondval {
                   11125:     my ($allpathcond) = @_;
                   11126:     my $result=0;
                   11127:     if ($env{'request.course.id'}
                   11128: 	&& defined($allpathcond)) {
                   11129: 	my $operand='|';
                   11130: 	my @stack;
                   11131: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11132: 	    if ($chunk eq '(') {
                   11133: 		push @stack,($operand,$result);
                   11134: 	    } elsif ($chunk eq ')') {
                   11135: 		my $before=pop @stack;
                   11136: 		if (pop @stack eq '&') {
                   11137: 		    $result=$result>$before?$before:$result;
                   11138: 		} else {
                   11139: 		    $result=$result>$before?$result:$before;
                   11140: 		}
                   11141: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11142: 		$operand=$chunk;
                   11143: 	    } else {
                   11144: 		my $new=directcondval($chunk);
                   11145: 		if ($operand eq '&') {
                   11146: 		    $result=$result>$new?$new:$result;
                   11147: 		} else {
                   11148: 		    $result=$result>$new?$result:$new;
                   11149: 		}
                   11150: 	    }
                   11151: 	}
1.26      www      11152:     }
                   11153:     return $result;
1.421     albertel 11154: }
                   11155: 
                   11156: # ---------------------------------------------------- Devalidate courseresdata
                   11157: 
                   11158: sub devalidatecourseresdata {
                   11159:     my ($coursenum,$coursedomain)=@_;
                   11160:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11161:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11162: }
                   11163: 
1.763     www      11164: 
1.200     www      11165: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11166: #
                   11167: #  Parameters:
                   11168: #      $coursenum    - Number of the course.
                   11169: #      $coursedomain - Domain at which the course was created.
                   11170: #  Returns:
                   11171: #     A hash of the course parameters along (I think) with timestamps
                   11172: #     and version info.
1.877     foxr     11173: 
1.624     albertel 11174: sub get_courseresdata {
                   11175:     my ($coursenum,$coursedomain)=@_;
1.200     www      11176:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11177:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11178:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11179:     my %dumpreply;
1.417     albertel 11180:     unless (defined($cached)) {
1.624     albertel 11181: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11182: 	$result=\%dumpreply;
1.251     albertel 11183: 	my ($tmp) = keys(%dumpreply);
                   11184: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11185: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11186: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11187: 	    return $tmp;
1.416     albertel 11188: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11189: 	    $result=undef;
1.599     albertel 11190: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11191: 	}
                   11192:     }
1.624     albertel 11193:     return $result;
                   11194: }
                   11195: 
1.633     albertel 11196: sub devalidateuserresdata {
                   11197:     my ($uname,$udom)=@_;
                   11198:     my $hashid="$udom:$uname";
                   11199:     &devalidate_cache_new('userres',$hashid);
                   11200: }
                   11201: 
1.624     albertel 11202: sub get_userresdata {
                   11203:     my ($uname,$udom)=@_;
                   11204:     #most student don\'t have any data set, check if there is some data
                   11205:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11206: 
                   11207:     my $hashid="$udom:$uname";
                   11208:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11209:     if (!defined($cached)) {
                   11210: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11211: 	$result=\%resourcedata;
                   11212: 	&do_cache_new('userres',$hashid,$result,600);
                   11213:     }
                   11214:     my ($tmp)=keys(%$result);
                   11215:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11216: 	return $result;
                   11217:     }
                   11218:     #error 2 occurs when the .db doesn't exist
                   11219:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11220:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11221: 	    &logthis("<font color=\"blue\">WARNING:".
                   11222: 		     " Trying to get resource data for ".
                   11223: 		     $uname." at ".$udom.": ".
                   11224: 		     $tmp."</font>");
                   11225:         }
1.624     albertel 11226:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11227: 	#&EXT_cache_set($udom,$uname);
                   11228: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11229: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11230:     }
                   11231:     return $tmp;
                   11232: }
1.879     foxr     11233: #----------------------------------------------- resdata - return resource data
                   11234: #  Purpose:
                   11235: #    Return resource data for either users or for a course.
                   11236: #  Parameters:
                   11237: #     $name      - Course/user name.
                   11238: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11239:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11240: #     @which     - Array of names of resources desired.
                   11241: #  Returns:
                   11242: #     The value of the first reasource in @which that is found in the
                   11243: #     resource hash.
                   11244: #  Exceptional Conditions:
                   11245: #     If the $type passed in is not valid (not the string 'course' or 
                   11246: #     'user', an undefined  reference is returned.
                   11247: #     If none of the resources are found, an undef is returned
1.624     albertel 11248: sub resdata {
                   11249:     my ($name,$domain,$type,@which)=@_;
                   11250:     my $result;
                   11251:     if ($type eq 'course') {
                   11252: 	$result=&get_courseresdata($name,$domain);
                   11253:     } elsif ($type eq 'user') {
                   11254: 	$result=&get_userresdata($name,$domain);
                   11255:     }
                   11256:     if (!ref($result)) { return $result; }    
1.251     albertel 11257:     foreach my $item (@which) {
1.1172.2.118.  .1(raebu 11258:20):         if (ref($item) eq 'ARRAY') {
                   11259:20): 	    if (defined($result->{$item->[0]})) {
                   11260:20): 	        return [$result->{$item->[0]},$item->[1]];
                   11261:20): 	    }
                   11262:20):         }
1.250     albertel 11263:     }
1.291     albertel 11264:     return undef;
1.200     www      11265: }
                   11266: 
1.1172.2.118.  .1(raebu 11267:20): sub get_domain_ltitools {
                   11268:20):     my ($cdom) = @_;
                   11269:20):     my %ltitools;
                   11270:20):     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   11271:20):     if (defined($cached)) {
                   11272:20):         if (ref($result) eq 'HASH') {
                   11273:20):             %ltitools = %{$result};
                   11274:20):         }
                   11275:20):     } else {
                   11276:20):         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   11277:20):         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   11278:20):             %ltitools = %{$domconfig{'ltitools'}};
                   11279:20):             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   11280:20):             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   11281:20):                 foreach my $id (keys(%ltitools)) {
                   11282:20):                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   11283:20):                         foreach my $item ('key','secret') {
                   11284:20):                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   11285:20):                         }
                   11286:20):                     }
                   11287:20):                 }
                   11288:20):             }
                   11289:20):         }
                   11290:20):         my $cachetime = 24*60*60;
                   11291:20):         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   11292:20):     }
                   11293:20):     return %ltitools;
                   11294:20): }
                   11295:20): 
1.1172.2.31  raeburn  11296: sub get_numsuppfiles {
                   11297:     my ($cnum,$cdom,$ignorecache)=@_;
                   11298:     my $hashid=$cnum.':'.$cdom;
                   11299:     my ($suppcount,$cached);
                   11300:     unless ($ignorecache) {
                   11301:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11302:     }
                   11303:     unless (defined($cached)) {
                   11304:         my $chome=&homeserver($cnum,$cdom);
                   11305:         unless ($chome eq 'no_host') {
                   11306:             ($suppcount,my $errors) = (0,0);
                   11307:             my $suppmap = 'supplemental.sequence';
                   11308:             ($suppcount,$errors) =
                   11309:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11310:         }
                   11311:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11312:     }
                   11313:     return $suppcount;
                   11314: }
                   11315: 
1.379     matthew  11316: #
                   11317: # EXT resource caching routines
                   11318: #
                   11319: 
                   11320: sub clear_EXT_cache_status {
1.383     albertel 11321:     &delenv('cache.EXT.');
1.379     matthew  11322: }
                   11323: 
                   11324: sub EXT_cache_status {
                   11325:     my ($target_domain,$target_user) = @_;
1.383     albertel 11326:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11327:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11328:         # We know already the user has no data
                   11329:         return 1;
                   11330:     } else {
                   11331:         return 0;
                   11332:     }
                   11333: }
                   11334: 
                   11335: sub EXT_cache_set {
                   11336:     my ($target_domain,$target_user) = @_;
1.383     albertel 11337:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11338:     #&appenv({$cachename => time});
1.379     matthew  11339: }
                   11340: 
1.28      www      11341: # --------------------------------------------------------- Value of a Variable
1.58      www      11342: sub EXT {
1.715     albertel 11343: 
1.1172.2.28  raeburn  11344:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11345:     unless ($varname) { return ''; }
1.218     albertel 11346:     #get real user name/domain, courseid and symb
                   11347:     my $courseid;
1.359     albertel 11348:     my $publicuser;
1.427     www      11349:     if ($symbparm) {
                   11350: 	$symbparm=&get_symb_from_alias($symbparm);
                   11351:     }
1.218     albertel 11352:     if (!($uname && $udom)) {
1.790     albertel 11353:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11354:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11355:     } else {
1.620     albertel 11356: 	$courseid=$env{'request.course.id'};
1.218     albertel 11357:     }
1.48      www      11358:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11359:     my $rest;
1.320     albertel 11360:     if (defined($therest[0])) {
1.48      www      11361:        $rest=join('.',@therest);
                   11362:     } else {
                   11363:        $rest='';
                   11364:     }
1.320     albertel 11365: 
1.57      www      11366:     my $qualifierrest=$qualifier;
                   11367:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11368:     my $spacequalifierrest=$space;
                   11369:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11370:     if ($realm eq 'user') {
1.48      www      11371: # --------------------------------------------------------------- user.resource
                   11372: 	if ($space eq 'resource') {
1.651     albertel 11373: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11374: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11375: 		 &&
1.744     albertel 11376: 		 ($symbparm eq &symbread()) ) {	
                   11377: 		# if we are in the middle of processing the resource the
                   11378: 		# get the value we are planning on committing
                   11379:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11380:                     return $Apache::lonhomework::results{$qualifierrest};
                   11381:                 } else {
                   11382:                     return $Apache::lonhomework::history{$qualifierrest};
                   11383:                 }
1.335     albertel 11384: 	    } else {
1.359     albertel 11385: 		my %restored;
1.620     albertel 11386: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11387: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11388: 		} else {
                   11389: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11390: 		}
1.335     albertel 11391: 		return $restored{$qualifierrest};
                   11392: 	    }
1.48      www      11393: # ----------------------------------------------------------------- user.access
                   11394:         } elsif ($space eq 'access') {
1.218     albertel 11395: 	    # FIXME - not supporting calls for a specific user
1.48      www      11396:             return &allowed($qualifier,$rest);
                   11397: # ------------------------------------------ user.preferences, user.environment
                   11398:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11399: 	    if (($uname eq $env{'user.name'}) &&
                   11400: 		($udom eq $env{'user.domain'})) {
                   11401: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11402: 	    } else {
1.359     albertel 11403: 		my %returnhash;
                   11404: 		if (!$publicuser) {
                   11405: 		    %returnhash=&userenvironment($udom,$uname,
                   11406: 						 $qualifierrest);
                   11407: 		}
1.218     albertel 11408: 		return $returnhash{$qualifierrest};
                   11409: 	    }
1.48      www      11410: # ----------------------------------------------------------------- user.course
                   11411:         } elsif ($space eq 'course') {
1.218     albertel 11412: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11413:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11414: # ------------------------------------------------------------------- user.role
                   11415:         } elsif ($space eq 'role') {
1.218     albertel 11416: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11417:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11418:             if ($qualifier eq 'value') {
                   11419: 		return $role;
                   11420:             } elsif ($qualifier eq 'extent') {
                   11421:                 return $where;
                   11422:             }
                   11423: # ----------------------------------------------------------------- user.domain
                   11424:         } elsif ($space eq 'domain') {
1.218     albertel 11425:             return $udom;
1.48      www      11426: # ------------------------------------------------------------------- user.name
                   11427:         } elsif ($space eq 'name') {
1.218     albertel 11428:             return $uname;
1.48      www      11429: # ---------------------------------------------------- Any other user namespace
1.29      www      11430:         } else {
1.359     albertel 11431: 	    my %reply;
                   11432: 	    if (!$publicuser) {
                   11433: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11434: 	    }
                   11435: 	    return $reply{$qualifierrest};
1.48      www      11436:         }
1.236     www      11437:     } elsif ($realm eq 'query') {
                   11438: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11439:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11440: 						[$spacequalifierrest]);
1.620     albertel 11441: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11442:    } elsif ($realm eq 'request') {
1.48      www      11443: # ------------------------------------------------------------- request.browser
                   11444:         if ($space eq 'browser') {
1.1145    bisitz   11445:             return $env{'browser.'.$qualifier};
1.57      www      11446: # ------------------------------------------------------------ request.filename
                   11447:         } else {
1.620     albertel 11448:             return $env{'request.'.$spacequalifierrest};
1.29      www      11449:         }
1.28      www      11450:     } elsif ($realm eq 'course') {
1.48      www      11451: # ---------------------------------------------------------- course.description
1.620     albertel 11452:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11453:     } elsif ($realm eq 'resource') {
1.165     www      11454: 
1.620     albertel 11455: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11456: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11457: 	}
1.693     albertel 11458: 
1.1172.2.30  raeburn  11459:         if ($qualifier eq '') {
                   11460: 	    if ($space eq 'title') {
                   11461: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11462: 	        return &gettitle($symbparm);
                   11463: 	    }
1.693     albertel 11464: 	
1.1172.2.30  raeburn  11465: 	    if ($space eq 'map') {
                   11466: 	        my ($map) = &decode_symb($symbparm);
                   11467: 	        return &symbread($map);
                   11468: 	    }
                   11469:             if ($space eq 'maptitle') {
                   11470:                 my ($map) = &decode_symb($symbparm);
                   11471:                 return &gettitle($map);
                   11472:             }
                   11473: 	    if ($space eq 'filename') {
                   11474: 	        if ($symbparm) {
                   11475: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11476: 	        }
                   11477: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11478: 	    }
1.1172.2.30  raeburn  11479: 
                   11480:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11481:                 if ($space eq 'visibleparts') {
                   11482:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11483:                     my $item;
                   11484:                     if (ref($navmap)) {
                   11485:                         my $res = $navmap->getBySymb($symbparm);
                   11486:                         my $parts = $res->parts();
                   11487:                         if (ref($parts) eq 'ARRAY') {
                   11488:                             $item = join(',',@{$parts});
                   11489:                         }
                   11490:                         undef($navmap);
                   11491:                     }
                   11492:                     return $item;
                   11493:                 }
                   11494:             }
                   11495:         }
1.693     albertel 11496: 
                   11497: 	my ($section, $group, @groups);
1.593     albertel 11498: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11499:         if (($courseid eq '') && ($cid)) {
                   11500:             $courseid = $cid;
                   11501:         }
                   11502: 	if (($symbparm && $courseid) && 
                   11503: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11504: 
1.218     albertel 11505: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11506: 
1.60      www      11507: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11508: 	    my $symbp=$symbparm;
1.735     albertel 11509: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11510: 
                   11511: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11512: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11513: 
1.620     albertel 11514: 	    if (($env{'user.name'} eq $uname) &&
                   11515: 		($env{'user.domain'} eq $udom)) {
                   11516: 		$section=$env{'request.course.sec'};
1.733     raeburn  11517:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11518:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11519: 	    } else {
1.539     albertel 11520: 		if (! defined($usection)) {
1.551     albertel 11521: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11522: 		} else {
                   11523: 		    $section = $usection;
                   11524: 		}
1.733     raeburn  11525:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11526: 	    }
                   11527: 
                   11528: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11529: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11530: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11531: 
1.593     albertel 11532: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11533: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11534: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11535: 
1.60      www      11536: # ----------------------------------------------------------- first, check user
1.624     albertel 11537: 
                   11538: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11539: 				       ([$courselevelr,'resource'],
                   11540: 					[$courselevelm,'map'     ],
                   11541: 					[$courselevel, 'course'  ]));
1.931     albertel 11542: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11543: 
1.594     albertel 11544: # ------------------------------------------------ second, check some of course
1.684     raeburn  11545:             my $coursereply;
1.691     raeburn  11546:             if (@groups > 0) {
                   11547:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11548:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11549:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11550:             }
1.96      www      11551: 
1.684     raeburn  11552: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11553: 				  $env{'course.'.$courseid.'.domain'},
                   11554: 				  'course',
                   11555: 				  ([$seclevelr,   'resource'],
                   11556: 				   [$seclevelm,   'map'     ],
                   11557: 				   [$seclevel,    'course'  ],
                   11558: 				   [$courselevelr,'resource']));
                   11559: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11560: 
1.60      www      11561: # ------------------------------------------------------ third, check map parms
1.218     albertel 11562: 	    my %parmhash=();
                   11563: 	    my $thisparm='';
                   11564: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11565: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11566: 		    &GDBM_READER(),0640)) {
1.218     albertel 11567: 		$thisparm=$parmhash{$symbparm};
                   11568: 		untie(%parmhash);
                   11569: 	    }
1.927     albertel 11570: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11571: 	}
1.594     albertel 11572: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11573: 
1.218     albertel 11574: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11575: 	my $filename;
                   11576: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11577: 	if ($symbparm) {
1.409     www      11578: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11579: 	} else {
1.620     albertel 11580: 	    $filename=$env{'request.filename'};
1.282     albertel 11581: 	}
                   11582: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11583: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11584: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11585: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11586: 
1.927     albertel 11587: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11588: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11589: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11590: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11591: 				     $env{'course.'.$courseid.'.domain'},
                   11592: 				     'course',
1.927     albertel 11593: 				     ([$courselevelm,'map'   ],
                   11594: 				      [$courselevel, 'course']));
                   11595: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11596: 	}
1.145     www      11597: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11598: 	unless ($space eq '0') {
1.336     albertel 11599: 	    my @parts=split(/_/,$space);
                   11600: 	    my $id=pop(@parts);
                   11601: 	    my $part=join('_',@parts);
                   11602: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11603: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11604: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11605: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11606: 	}
1.395     albertel 11607: 	if ($recurse) { return undef; }
                   11608: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11609: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11610: # ---------------------------------------------------- Any other user namespace
                   11611:     } elsif ($realm eq 'environment') {
                   11612: # ----------------------------------------------------------------- environment
1.620     albertel 11613: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11614: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11615: 	} else {
1.770     albertel 11616: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11617: 		return '';
                   11618: 	    }
1.219     albertel 11619: 	    my %returnhash=&userenvironment($udom,$uname,
                   11620: 					    $spacequalifierrest);
                   11621: 	    return $returnhash{$spacequalifierrest};
                   11622: 	}
1.28      www      11623:     } elsif ($realm eq 'system') {
1.48      www      11624: # ----------------------------------------------------------------- system.time
                   11625: 	if ($space eq 'time') {
                   11626: 	    return time;
                   11627:         }
1.696     albertel 11628:     } elsif ($realm eq 'server') {
                   11629: # ----------------------------------------------------------------- system.time
                   11630: 	if ($space eq 'name') {
                   11631: 	    return $ENV{'SERVER_NAME'};
                   11632:         }
1.28      www      11633:     }
1.48      www      11634:     return '';
1.61      www      11635: }
                   11636: 
1.927     albertel 11637: sub get_reply {
                   11638:     my ($reply_value) = @_;
1.940     raeburn  11639:     if (ref($reply_value) eq 'ARRAY') {
                   11640:         if (wantarray) {
                   11641: 	    return @$reply_value;
                   11642:         }
                   11643:         return $reply_value->[0];
                   11644:     } else {
                   11645:         return $reply_value;
1.927     albertel 11646:     }
                   11647: }
                   11648: 
1.691     raeburn  11649: sub check_group_parms {
                   11650:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11651:     my @groupitems = ();
                   11652:     my $resultitem;
1.927     albertel 11653:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11654:     foreach my $group (@{$groups}) {
                   11655:         foreach my $level (@levels) {
1.927     albertel 11656:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11657:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11658:         }
                   11659:     }
                   11660:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11661:                             $env{'course.'.$courseid.'.domain'},
                   11662:                                      'course',@groupitems);
                   11663:     return $coursereply;
                   11664: }
                   11665: 
                   11666: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11667:     my ($courseid,@groups) = @_;
                   11668:     @groups = sort(@groups);
1.691     raeburn  11669:     return @groups;
                   11670: }
                   11671: 
1.395     albertel 11672: sub packages_tab_default {
                   11673:     my ($uri,$varname)=@_;
                   11674:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11675: 
                   11676:     my (@extension,@specifics,$do_default);
                   11677:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11678: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11679: 	if ($pack_type eq 'default') {
                   11680: 	    $do_default=1;
                   11681: 	} elsif ($pack_type eq 'extension') {
                   11682: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11683: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11684: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11685: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11686: 	}
                   11687:     }
                   11688:     # first look for a package that matches the requested part id
                   11689:     foreach my $package (@specifics) {
                   11690: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11691: 	next if ($pack_part ne $part);
                   11692: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11693: 	    return $packagetab{"$pack_type&$name&default"};
                   11694: 	}
                   11695:     }
                   11696:     # look for any possible matching non extension_ package
                   11697:     foreach my $package (@specifics) {
                   11698: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11699: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11700: 	    return $packagetab{"$pack_type&$name&default"};
                   11701: 	}
1.585     albertel 11702: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11703: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11704: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11705: 	}
                   11706:     }
1.738     albertel 11707:     # look for any posible extension_ match
                   11708:     foreach my $package (@extension) {
                   11709: 	my ($package,$pack_type)=@{$package};
                   11710: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11711: 	    return $packagetab{"$pack_type&$name&default"};
                   11712: 	}
                   11713: 	if (defined($packagetab{$package."&$name&default"})) {
                   11714: 	    return $packagetab{$package."&$name&default"};
                   11715: 	}
                   11716:     }
                   11717:     # look for a global default setting
                   11718:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11719: 	return $packagetab{"default&$name&default"};
                   11720:     }
1.395     albertel 11721:     return undef;
                   11722: }
                   11723: 
1.334     albertel 11724: sub add_prefix_and_part {
                   11725:     my ($prefix,$part)=@_;
                   11726:     my $keyroot;
                   11727:     if (defined($prefix) && $prefix !~ /^__/) {
                   11728: 	# prefix that has a part already
                   11729: 	$keyroot=$prefix;
                   11730:     } elsif (defined($prefix)) {
                   11731: 	# prefix that is missing a part
                   11732: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11733:     } else {
                   11734: 	# no prefix at all
                   11735: 	if (defined($part)) { $keyroot='_'.$part; }
                   11736:     }
                   11737:     return $keyroot;
                   11738: }
                   11739: 
1.71      www      11740: # ---------------------------------------------------------------- Get metadata
                   11741: 
1.599     albertel 11742: my %metaentry;
1.1070    www      11743: my %importedpartids;
1.1172.2.99  raeburn  11744: my %importedrespids;
1.71      www      11745: sub metadata {
1.176     www      11746:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11747:     $uri=&declutter($uri);
1.288     albertel 11748:     # if it is a non metadata possible uri return quickly
1.529     albertel 11749:     if (($uri eq '') || 
                   11750: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11751:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11752:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11753: 	return undef;
                   11754:     }
1.1172.2.49  raeburn  11755:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11756: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11757: 	return undef;
1.288     albertel 11758:     }
1.73      www      11759:     my $filename=$uri;
                   11760:     $uri=~s/\.meta$//;
1.172     www      11761: #
                   11762: # Is the metadata already cached?
1.177     www      11763: # Look at timestamp of caching
1.172     www      11764: # Everything is cached by the main uri, libraries are never directly cached
                   11765: #
1.428     albertel 11766:     if (!defined($liburi)) {
1.599     albertel 11767: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11768: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11769:     }
                   11770:     {
1.1069    www      11771: # Imported parts would go here
1.1172.2.99  raeburn  11772:         my @origfiletagids=();
1.1069    www      11773:         my $importedparts=0;
1.1172.2.99  raeburn  11774: 
                   11775: # Imported responseids would go here
                   11776:         my $importedresponses=0;
1.172     www      11777: #
                   11778: # Is this a recursive call for a library?
                   11779: #
1.599     albertel 11780: #	if (! exists($metacache{$uri})) {
                   11781: #	    $metacache{$uri}={};
                   11782: #	}
1.924     albertel 11783: 	my $cachetime = 60*60;
1.171     www      11784:         if ($liburi) {
                   11785: 	    $liburi=&declutter($liburi);
                   11786:             $filename=$liburi;
1.401     bowersj2 11787:         } else {
1.599     albertel 11788: 	    &devalidate_cache_new('meta',$uri);
                   11789: 	    undef(%metaentry);
1.401     bowersj2 11790: 	}
1.140     www      11791:         my %metathesekeys=();
1.73      www      11792:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11793: 	my $metastring;
1.1140    www      11794: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11795: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11796: 	    $metastring = 
1.929     albertel 11797: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11798: 					  ('grade_target' => 'meta'));
                   11799: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11800: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11801:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11802: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11803: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11804: 	    $metastring=&getfile($file);
1.489     albertel 11805: 	}
1.208     albertel 11806:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11807:         my $token;
1.140     www      11808:         undef %metathesekeys;
1.71      www      11809:         while ($token=$parser->get_token) {
1.339     albertel 11810: 	    if ($token->[0] eq 'S') {
                   11811: 		if (defined($token->[2]->{'package'})) {
1.172     www      11812: #
                   11813: # This is a package - get package info
                   11814: #
1.339     albertel 11815: 		    my $package=$token->[2]->{'package'};
                   11816: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11817: 		    if (defined($token->[2]->{'id'})) { 
                   11818: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11819: 		    }
1.599     albertel 11820: 		    if ($metaentry{':packages'}) {
                   11821: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11822: 		    } else {
1.599     albertel 11823: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11824: 		    }
1.736     albertel 11825: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11826: 			my $part=$keyroot;
                   11827: 			$part=~s/^\_//;
1.736     albertel 11828: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11829: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11830: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11831: 			    # ignore package.tab specified default values
                   11832:                             # here &package_tab_default() will fetch those
                   11833: 			    if ($subp eq 'default') { next; }
1.736     albertel 11834: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11835: 			    my $unikey;
                   11836: 			    if ($pack =~ /_0$/) {
                   11837: 				$unikey='parameter_0_'.$name;
                   11838: 				$part=0;
                   11839: 			    } else {
                   11840: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11841: 			    }
1.339     albertel 11842: 			    if ($subp eq 'display') {
                   11843: 				$value.=' [Part: '.$part.']';
                   11844: 			    }
1.599     albertel 11845: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11846: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11847: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11848: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11849: 			    }
1.599     albertel 11850: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11851: 				$metaentry{':'.$unikey}=
                   11852: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11853: 			    }
1.339     albertel 11854: 			}
                   11855: 		    }
                   11856: 		} else {
1.172     www      11857: #
                   11858: # This is not a package - some other kind of start tag
1.339     albertel 11859: #
                   11860: 		    my $entry=$token->[1];
1.1068    www      11861: 		    my $unikey='';
1.175     www      11862: 
1.339     albertel 11863: 		    if ($entry eq 'import') {
1.175     www      11864: #
                   11865: # Importing a library here
1.339     albertel 11866: #
1.1067    www      11867:                         my $location=$parser->get_text('/import');
                   11868:                         my $dir=$filename;
                   11869:                         $dir=~s|[^/]*$||;
                   11870:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11871: 
                   11872:                         my $importid=$token->[2]->{'id'};
1.1068    www      11873:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11874: #
                   11875: # Check metadata for imported file to
                   11876: # see if it contained response items
                   11877: #
                   11878:                         my %currmetaentry = %metaentry;
                   11879:                         my $libresponseorder = &metadata($location,'responseorder');
                   11880:                         my $origfile;
                   11881:                         if ($libresponseorder ne '') {
                   11882:                             if ($#origfiletagids<0) {
                   11883:                                 undef(%importedrespids);
                   11884:                                 undef(%importedpartids);
                   11885:                             }
                   11886:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11887:                             if (@{$importedrespids{$importid}} > 0) {
                   11888:                                 $importedresponses = 1;
                   11889: # We need to get the original file and the imported file to get the response order correct
                   11890: # Load and inspect original file
                   11891:                                 if ($#origfiletagids<0) {
                   11892:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11893:                                     $origfile=&getfile($origfilelocation);
                   11894:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11895:                                 }
                   11896:                             }
                   11897:                         }
                   11898: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11899: # hash populated for imported library file
                   11900:                         %metaentry = %currmetaentry;
                   11901:                         undef(%currmetaentry);
1.1068    www      11902:                         if ($importmode eq 'problem') {
1.1069    www      11903: # Import as problem/response
1.1068    www      11904:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11905:                         } elsif ($importmode eq 'part') {
                   11906: # Import as part(s)
1.1069    www      11907:                            $importedparts=1;
                   11908: # We need to get the original file and the imported file to get the part order correct
                   11909: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11910: # Load and inspect original file if we didn't do that already
                   11911:                            if ($#origfiletagids<0) {
                   11912:                                undef(%importedrespids);
                   11913:                                undef(%importedpartids);
                   11914:                                if ($origfile eq '') {
                   11915:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11916:                                    $origfile=&getfile($origfilelocation);
                   11917:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11918:                                }
1.1070    www      11919:                            }
                   11920: 
1.1069    www      11921: # Load and inspect imported file
                   11922:                            my $impfile=&getfile($location);
                   11923:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11924:                            if ($#impfilepartids>=0) {
                   11925: # This problem had parts
1.1070    www      11926:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11927:                            } else {
                   11928: # Importing by turning a single problem into a problem part
                   11929: # It gets the import-tags ID as part-ID
                   11930:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11931:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11932:                            }
1.1068    www      11933:                         } else {
                   11934: # Normal import
                   11935:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11936:                            if (defined($token->[2]->{'id'})) {
                   11937:                               $unikey.='_'.$token->[2]->{'id'};
                   11938:                            }
1.1067    www      11939:                         }
                   11940: 
1.339     albertel 11941: 			if ($depthcount<20) {
1.736     albertel 11942: 			    my $metadata = 
                   11943: 				&metadata($uri,'keys', $location,$unikey,
                   11944: 					  $depthcount+1);
                   11945: 			    foreach my $meta (split(',',$metadata)) {
                   11946: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11947: 				$metathesekeys{$meta}=1;
1.339     albertel 11948: 			    }
1.1068    www      11949: 			
                   11950:                         }
1.1067    www      11951: 		    } else {
                   11952: #
                   11953: # Not importing, some other kind of non-package, non-library start tag
                   11954: # 
                   11955:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11956:                         if (defined($token->[2]->{'id'})) {
                   11957:                             $unikey.='_'.$token->[2]->{'id'};
                   11958:                         }
1.339     albertel 11959: 			if (defined($token->[2]->{'name'})) { 
                   11960: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11961: 			}
                   11962: 			$metathesekeys{$unikey}=1;
1.736     albertel 11963: 			foreach my $param (@{$token->[3]}) {
                   11964: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11965: 				$token->[2]->{$param};
1.339     albertel 11966: 			}
                   11967: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11968: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11969: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11970: 		 # only ws inside the tag, and not in default, so use default
                   11971: 		 # as value
1.599     albertel 11972: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11973: 			} elsif ( $internaltext =~ /\S/ ) {
                   11974: 		  # something interesting inside the tag
                   11975: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11976: 			} else {
1.908     albertel 11977: 		  # no interesting values, don't set a default
1.339     albertel 11978: 			}
1.172     www      11979: # end of not-a-package not-a-library import
1.339     albertel 11980: 		    }
1.172     www      11981: # end of not-a-package start tag
1.339     albertel 11982: 		}
1.172     www      11983: # the next is the end of "start tag"
1.339     albertel 11984: 	    }
                   11985: 	}
1.483     albertel 11986: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11987: 	$extension = lc($extension);
                   11988: 	if ($extension eq 'htm') { $extension='html'; }
                   11989: 
1.737     albertel 11990: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11991: 	    #no specific packages #how's our extension
                   11992: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11993: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11994: 					 \%metathesekeys);
                   11995: 	}
1.883     albertel 11996: 
                   11997: 	if (!exists($metaentry{':packages'})
                   11998: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11999: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12000: 		#no specific packages well let's get default then
                   12001: 		if ($key!~/^default&/) { next; }
1.488     albertel 12002: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12003: 					     \%metathesekeys);
                   12004: 	    }
                   12005: 	}
1.338     www      12006: # are there custom rights to evaluate
1.599     albertel 12007: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12008: 
1.338     www      12009:     #
                   12010:     # Importing a rights file here
1.339     albertel 12011:     #
                   12012: 	    unless ($depthcount) {
1.599     albertel 12013: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12014: 		my $dir=$filename;
                   12015: 		$dir=~s|[^/]*$||;
                   12016: 		$location=&filelocation($dir,$location);
1.736     albertel 12017: 		my $rights_metadata =
                   12018: 		    &metadata($uri,'keys',$location,'_rights',
                   12019: 			      $depthcount+1);
                   12020: 		foreach my $rights (split(',',$rights_metadata)) {
                   12021: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12022: 		    $metathesekeys{$rights}=1;
1.339     albertel 12023: 		}
                   12024: 	    }
                   12025: 	}
1.737     albertel 12026: 	# uniqifiy package listing
                   12027: 	my %seen;
                   12028: 	my @uniq_packages =
                   12029: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12030: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12031: 
1.1172.2.99  raeburn  12032:         if (($importedresponses) || ($importedparts)) {
                   12033:             if ($importedparts) {
1.1070    www      12034: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12035:                 $metaentry{':partorder'}='';
                   12036:                 $metathesekeys{'partorder'}=1;
                   12037:             }
                   12038:             if ($importedresponses) {
                   12039: # We had imported responses and need to rebuild responseorder
                   12040:                 $metaentry{':responseorder'}='';
                   12041:                 $metathesekeys{'responseorder'}=1;
                   12042:             }
                   12043:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12044:                 my $origid = $origfiletagids[$index+1];
                   12045:                 if ($origfiletagids[$index] eq 'part') {
                   12046: # Original part, part of the problem
                   12047:                     if ($importedparts) {
                   12048:                         $metaentry{':partorder'}.=','.$origid;
                   12049:                     }
                   12050:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12051:                     if ($importedparts) {
                   12052: # We have imported parts at this position
                   12053:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12054:                     }
                   12055:                     if ($importedresponses) {
                   12056: # We have imported responses at this position
                   12057:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12058:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12059:                         }
                   12060:                     }
                   12061:                 } else {
                   12062: # Original response item, part of the problem
                   12063:                     if ($importedresponses) {
                   12064:                         $metaentry{':responseorder'}.=','.$origid;
                   12065:                     }
                   12066:                 }
                   12067:             }
                   12068:             if ($importedparts) {
                   12069:                 $metaentry{':partorder'}=~s/^\,//;
                   12070:             }
                   12071:             if ($importedresponses) {
                   12072:                 $metaentry{':responseorder'}=~s/^\,//;
                   12073:             }
1.1070    www      12074:         }
                   12075: 
1.737     albertel 12076: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12077: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12078: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12079: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12080: # this is the end of "was not already recently cached
1.71      www      12081:     }
1.599     albertel 12082:     return $metaentry{':'.$what};
1.261     albertel 12083: }
                   12084: 
1.488     albertel 12085: sub metadata_create_package_def {
1.483     albertel 12086:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12087:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12088:     if ($subp eq 'default') { next; }
                   12089:     
1.599     albertel 12090:     if (defined($metaentry{':packages'})) {
                   12091: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12092:     } else {
1.599     albertel 12093: 	$metaentry{':packages'}=$package;
1.483     albertel 12094:     }
                   12095:     my $value=$packagetab{$key};
                   12096:     my $unikey;
                   12097:     $unikey='parameter_0_'.$name;
1.599     albertel 12098:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12099:     $$metathesekeys{$unikey}=1;
1.599     albertel 12100:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12101: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12102:     }
1.599     albertel 12103:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12104: 	$metaentry{':'.$unikey}=
                   12105: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12106:     }
                   12107: }
                   12108: 
1.261     albertel 12109: sub metadata_generate_part0 {
                   12110:     my ($metadata,$metacache,$uri) = @_;
                   12111:     my %allnames;
1.737     albertel 12112:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12113: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12114: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12115: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12116: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12117: 	    $allnames{$name}=$part;
                   12118: 	  }
                   12119: 	}
                   12120:     }
                   12121:     foreach my $name (keys(%allnames)) {
                   12122:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12123:       my $key=":parameter_0_$name";
1.261     albertel 12124:       $$metacache{"$key.part"}='0';
                   12125:       $$metacache{"$key.name"}=$name;
1.428     albertel 12126:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12127: 					   $allnames{$name}.'_'.$name.
                   12128: 					   '.type'};
1.428     albertel 12129:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12130: 			     '.display'};
1.644     www      12131:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12132:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12133:       $$metacache{"$key.display"}=$olddis;
                   12134:     }
1.71      www      12135: }
                   12136: 
1.764     albertel 12137: # ------------------------------------------------------ Devalidate title cache
                   12138: 
                   12139: sub devalidate_title_cache {
                   12140:     my ($url)=@_;
                   12141:     if (!$env{'request.course.id'}) { return; }
                   12142:     my $symb=&symbread($url);
                   12143:     if (!$symb) { return; }
                   12144:     my $key=$env{'request.course.id'}."\0".$symb;
                   12145:     &devalidate_cache_new('title',$key);
                   12146: }
                   12147: 
1.1014    droeschl 12148: # ------------------------------------------------- Get the title of a course
                   12149: 
                   12150: sub current_course_title {
                   12151:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12152: }
1.301     www      12153: # ------------------------------------------------- Get the title of a resource
                   12154: 
                   12155: sub gettitle {
                   12156:     my $urlsymb=shift;
                   12157:     my $symb=&symbread($urlsymb);
1.534     albertel 12158:     if ($symb) {
1.620     albertel 12159: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12160: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12161: 	if (defined($cached)) { 
                   12162: 	    return $result;
                   12163: 	}
1.534     albertel 12164: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12165: 	my $title='';
1.907     albertel 12166: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12167: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12168: 	} else {
                   12169: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12170: 		    &GDBM_READER(),0640)) {
                   12171: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12172: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12173: 		untie(%bighash);
                   12174: 	    }
1.534     albertel 12175: 	}
                   12176: 	$title=~s/\&colon\;/\:/gs;
                   12177: 	if ($title) {
1.1159    www      12178: # Remember both $symb and $title for dynamic metadata
                   12179:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12180:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12181: # Cache this title and then return it
1.599     albertel 12182: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12183: 	}
                   12184: 	$urlsymb=$url;
                   12185:     }
                   12186:     my $title=&metadata($urlsymb,'title');
                   12187:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12188:     return $title;
1.301     www      12189: }
1.613     albertel 12190: 
1.614     albertel 12191: sub get_slot {
                   12192:     my ($which,$cnum,$cdom)=@_;
                   12193:     if (!$cnum || !$cdom) {
1.790     albertel 12194: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12195: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12196: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12197:     }
1.703     albertel 12198:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12199:     my %slotinfo;
                   12200:     if (exists($remembered{$key})) {
                   12201: 	$slotinfo{$which} = $remembered{$key};
                   12202:     } else {
                   12203: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12204: 	&Apache::lonhomework::showhash(%slotinfo);
                   12205: 	my ($tmp)=keys(%slotinfo);
                   12206: 	if ($tmp=~/^error:/) { return (); }
                   12207: 	$remembered{$key} = $slotinfo{$which};
                   12208:     }
1.616     albertel 12209:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12210: 	return %{$slotinfo{$which}};
                   12211:     }
                   12212:     return $slotinfo{$which};
1.614     albertel 12213: }
1.1150    raeburn  12214: 
                   12215: sub get_reservable_slots {
                   12216:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12217:     my $now = time;
                   12218:     my $reservable_info;
                   12219:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12220:     if (exists($remembered{$key})) {
                   12221:         $reservable_info = $remembered{$key};
                   12222:     } else {
                   12223:         my %resv;
                   12224:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12225:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12226:         $reservable_info = \%resv;
                   12227:         $remembered{$key} = $reservable_info;
                   12228:     }
                   12229:     return $reservable_info;
                   12230: }
                   12231: 
                   12232: sub get_course_slots {
                   12233:     my ($cnum,$cdom) = @_;
                   12234:     my $hashid=$cnum.':'.$cdom;
                   12235:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12236:     if (defined($cached)) {
                   12237:         if (ref($result) eq 'HASH') {
                   12238:             return %{$result};
                   12239:         }
                   12240:     } else {
                   12241:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12242:         my ($tmp) = keys(%slots);
                   12243:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12244:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12245:             return %slots;
                   12246:         }
                   12247:     }
                   12248:     return;
                   12249: }
                   12250: 
                   12251: sub devalidate_slots_cache {
                   12252:     my ($cnum,$cdom)=@_;
                   12253:     my $hashid=$cnum.':'.$cdom;
                   12254:     &devalidate_cache_new('allslots',$hashid);
                   12255: }
                   12256: 
1.1172.2.8  raeburn  12257: sub get_coursechange {
                   12258:     my ($cdom,$cnum) = @_;
                   12259:     if ($cdom eq '' || $cnum eq '') {
                   12260:         return unless ($env{'request.course.id'});
                   12261:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12262:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12263:     }
                   12264:     my $hashid=$cdom.'_'.$cnum;
                   12265:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12266:     if ((defined($cached)) && ($change ne '')) {
                   12267:         return $change;
                   12268:     } else {
                   12269:         my %crshash;
                   12270:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12271:         if ($crshash{'internal.contentchange'} eq '') {
                   12272:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12273:             if ($change eq '') {
                   12274:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12275:                 $change = $crshash{'internal.created'};
                   12276:             }
                   12277:         } else {
                   12278:             $change = $crshash{'internal.contentchange'};
                   12279:         }
                   12280:         my $cachetime = 600;
                   12281:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12282:     }
                   12283:     return $change;
                   12284: }
                   12285: 
                   12286: sub devalidate_coursechange_cache {
                   12287:     my ($cnum,$cdom)=@_;
                   12288:     my $hashid=$cnum.':'.$cdom;
                   12289:     &devalidate_cache_new('crschange',$hashid);
                   12290: }
                   12291: 
1.31      www      12292: # ------------------------------------------------- Update symbolic store links
                   12293: 
                   12294: sub symblist {
                   12295:     my ($mapname,%newhash)=@_;
1.438     www      12296:     $mapname=&deversion(&declutter($mapname));
1.31      www      12297:     my %hash;
1.620     albertel 12298:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12299:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12300:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12301: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12302: 		next if ($url eq 'last_known'
                   12303: 			 && $env{'form.no_update_last_known'});
                   12304: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12305: 						    $newhash{$url}->[1],
                   12306: 						    $newhash{$url}->[0]);
1.191     harris41 12307:             }
1.31      www      12308:             if (untie(%hash)) {
                   12309: 		return 'ok';
                   12310:             }
                   12311:         }
                   12312:     }
                   12313:     return 'error';
1.212     www      12314: }
                   12315: 
                   12316: # --------------------------------------------------------------- Verify a symb
                   12317: 
                   12318: sub symbverify {
1.1172.2.11  raeburn  12319:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12320:     my $thisfn=$thisurl;
1.439     www      12321:     $thisfn=&declutter($thisfn);
1.215     www      12322: # direct jump to resource in page or to a sequence - will construct own symbs
                   12323:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12324: # check URL part
1.409     www      12325:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12326: 
1.431     www      12327:     unless ($url eq $thisfn) { return 0; }
1.213     www      12328: 
1.216     www      12329:     $symb=&symbclean($symb);
1.510     www      12330:     $thisurl=&deversion($thisurl);
1.439     www      12331:     $thisfn=&deversion($thisfn);
1.213     www      12332: 
                   12333:     my %bighash;
                   12334:     my $okay=0;
1.431     www      12335: 
1.620     albertel 12336:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12337:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  12338:         my $noclutter;
1.1032    raeburn  12339:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12340:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12341:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12342:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12343:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12344:                 $noclutter = 1;
                   12345:             }
                   12346:         }
                   12347:         my $ids;
                   12348:         if ($noclutter) {
                   12349:             $ids=$bighash{'ids_'.$thisurl};
                   12350:         } else {
                   12351:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12352:         }
1.1102    raeburn  12353:         unless ($ids) {
1.1172.2.13  raeburn  12354:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12355:             $ids=$bighash{$idkey};
1.216     www      12356:         }
                   12357:         if ($ids) {
                   12358: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12359:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12360:                 $symb =~ s/\?.+$//;
                   12361:             }
1.800     albertel 12362: 	    foreach my $id (split(/\,/,$ids)) {
                   12363: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12364:                if (
                   12365:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12366:    eq $symb) {
1.1172.2.11  raeburn  12367:                    if (ref($encstate)) {
                   12368:                        $$encstate = $bighash{'encrypted_'.$id};
                   12369:                    }
1.1172.2.13  raeburn  12370:                    if (($env{'request.role.adv'}) ||
                   12371:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12372:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12373:                        $okay=1;
                   12374:                        last;
                   12375:                    }
                   12376:                }
                   12377:            }
1.216     www      12378:         }
1.213     www      12379: 	untie(%bighash);
                   12380:     }
                   12381:     return $okay;
1.31      www      12382: }
                   12383: 
1.210     www      12384: # --------------------------------------------------------------- Clean-up symb
                   12385: 
                   12386: sub symbclean {
                   12387:     my $symb=shift;
1.568     albertel 12388:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12389: # remove version from map
                   12390:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12391: 
1.210     www      12392: # remove version from URL
                   12393:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12394: 
1.507     www      12395: # remove wrapper
                   12396: 
1.510     www      12397:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12398:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12399:     return $symb;
1.409     www      12400: }
                   12401: 
                   12402: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12403: 
                   12404: sub encode_symb {
                   12405:     my ($map,$resid,$url)=@_;
                   12406:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12407: }
1.409     www      12408: 
                   12409: sub decode_symb {
1.568     albertel 12410:     my $symb=shift;
                   12411:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12412:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12413:     return (&fixversion($map),$resid,&fixversion($url));
                   12414: }
                   12415: 
                   12416: sub fixversion {
                   12417:     my $fn=shift;
1.609     banghart 12418:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12419:     my %bighash;
                   12420:     my $uri=&clutter($fn);
1.620     albertel 12421:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12422: # is this cached?
1.599     albertel 12423:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12424:     if (defined($cached)) { return $result; }
                   12425: # unfortunately not cached, or expired
1.620     albertel 12426:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12427: 	    &GDBM_READER(),0640)) {
                   12428:  	if ($bighash{'version_'.$uri}) {
                   12429:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12430:  	    unless (($version eq 'mostrecent') || 
                   12431: 		    ($version==&getversion($uri))) {
1.440     www      12432:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12433:  	    }
                   12434:  	}
                   12435:  	untie %bighash;
1.413     www      12436:     }
1.599     albertel 12437:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12438: }
                   12439: 
                   12440: sub deversion {
                   12441:     my $url=shift;
                   12442:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12443:     return $url;
1.210     www      12444: }
                   12445: 
1.31      www      12446: # ------------------------------------------------------ Return symb list entry
                   12447: 
                   12448: sub symbread {
1.1172.2.66  raeburn  12449:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12450:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12451:     if (defined($env{$cache_str})) {
                   12452:         if ($ignorecachednull) {
                   12453:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12454:         } else {
                   12455:             return $env{$cache_str};
                   12456:         }
                   12457:     }
1.242     www      12458: # no filename provided? try from environment
1.1172.2.54  raeburn  12459:     unless ($thisfn) {
1.620     albertel 12460:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12461:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12462:         }
                   12463:         $thisfn=$env{'request.filename'};
1.44      www      12464:     }
1.569     albertel 12465:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12466: # is that filename actually a symb? Verify, clean, and return
                   12467:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12468: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12469: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12470: 	}
1.242     www      12471:     }
1.44      www      12472:     $thisfn=declutter($thisfn);
1.31      www      12473:     my %hash;
1.37      www      12474:     my %bighash;
                   12475:     my $syval='';
1.620     albertel 12476:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12477:         my $targetfn = $thisfn;
1.609     banghart 12478:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12479:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12480:         }
1.687     albertel 12481: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12482: 	    $targetfn=$1;
                   12483: 	}
1.620     albertel 12484:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12485:                       &GDBM_READER(),0640)) {
1.481     raeburn  12486: 	    $syval=$hash{$targetfn};
1.37      www      12487:             untie(%hash);
                   12488:         }
                   12489: # ---------------------------------------------------------- There was an entry
                   12490:         if ($syval) {
1.601     albertel 12491: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12492: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12493: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12494: 		    #return $env{$cache_str}='';
1.601     albertel 12495: 		#}    
                   12496: 		#$syval.=$1;
                   12497: 	    #}
1.37      www      12498:         } else {
                   12499: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12500:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12501:                             &GDBM_READER(),0640)) {
1.37      www      12502: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12503:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12504:               unless ($ids) { 
                   12505:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12506:               }
                   12507:               unless ($ids) {
                   12508: # alias?
                   12509: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12510:               }
1.37      www      12511:               if ($ids) {
                   12512: # ------------------------------------------------------------------- Has ID(s)
                   12513:                  my @possibilities=split(/\,/,$ids);
1.39      www      12514:                  if ($#possibilities==0) {
                   12515: # ----------------------------------------------- There is only one possibility
1.37      www      12516: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12517: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12518: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12519:                      if (ref($possibles) eq 'HASH') {
                   12520:                          $possibles->{$syval} = 1;
                   12521:                      }
                   12522:                      if ($checkforblock) {
                   12523:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12524:                          if (@blockers) {
                   12525:                              $syval = '';
                   12526:                              return;
                   12527:                          }
                   12528:                      }
                   12529:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12530: # ------------------------------------------ There is more than one possibility
                   12531:                      my $realpossible=0;
1.800     albertel 12532:                      foreach my $id (@possibilities) {
                   12533: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12534:                          my $canaccess;
                   12535:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12536:                              $canaccess = 1;
                   12537:                          } else {
                   12538:                              $canaccess = &allowed('bre',$file);
                   12539:                          }
                   12540:                          if ($canaccess) {
                   12541:          		     my ($mapid,$resid)=split(/\./,$id);
                   12542:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12543:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12544:                                                              $resid,$thisfn);
                   12545:                                  if (ref($possibles) eq 'HASH') {
                   12546:                                      $possibles->{$syval} = 1;
                   12547:                                  }
                   12548:                                  if ($checkforblock) {
                   12549:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12550:                                      unless (@blockers > 0) {
                   12551:                                          $syval = $poss_syval;
                   12552:                                          $realpossible++;
                   12553:                                      }
                   12554:                                  } else {
                   12555:                                      $syval = $poss_syval;
                   12556:                                      $realpossible++;
                   12557:                                  }
                   12558:                              }
1.39      www      12559: 			 }
1.191     harris41 12560:                      }
1.39      www      12561: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12562:                  } else {
                   12563:                      $syval='';
1.37      www      12564:                  }
                   12565: 	      }
1.1172.2.66  raeburn  12566:               untie(%bighash);
1.481     raeburn  12567:            }
1.31      www      12568:         }
1.62      www      12569:         if ($syval) {
1.620     albertel 12570: 	    return $env{$cache_str}=$syval;
1.62      www      12571:         }
1.31      www      12572:     }
1.949     raeburn  12573:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12574:     return $env{$cache_str}='';
1.31      www      12575: }
                   12576: 
                   12577: # ---------------------------------------------------------- Return random seed
                   12578: 
1.32      www      12579: sub numval {
                   12580:     my $txt=shift;
                   12581:     $txt=~tr/A-J/0-9/;
                   12582:     $txt=~tr/a-j/0-9/;
                   12583:     $txt=~tr/K-T/0-9/;
                   12584:     $txt=~tr/k-t/0-9/;
                   12585:     $txt=~tr/U-Z/0-5/;
                   12586:     $txt=~tr/u-z/0-5/;
                   12587:     $txt=~s/\D//g;
1.564     albertel 12588:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12589:     return int($txt);
1.368     albertel 12590: }
                   12591: 
1.484     albertel 12592: sub numval2 {
                   12593:     my $txt=shift;
                   12594:     $txt=~tr/A-J/0-9/;
                   12595:     $txt=~tr/a-j/0-9/;
                   12596:     $txt=~tr/K-T/0-9/;
                   12597:     $txt=~tr/k-t/0-9/;
                   12598:     $txt=~tr/U-Z/0-5/;
                   12599:     $txt=~tr/u-z/0-5/;
                   12600:     $txt=~s/\D//g;
                   12601:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12602:     my $total;
                   12603:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12604:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12605:     return int($total);
                   12606: }
                   12607: 
1.575     albertel 12608: sub numval3 {
                   12609:     use integer;
                   12610:     my $txt=shift;
                   12611:     $txt=~tr/A-J/0-9/;
                   12612:     $txt=~tr/a-j/0-9/;
                   12613:     $txt=~tr/K-T/0-9/;
                   12614:     $txt=~tr/k-t/0-9/;
                   12615:     $txt=~tr/U-Z/0-5/;
                   12616:     $txt=~tr/u-z/0-5/;
                   12617:     $txt=~s/\D//g;
                   12618:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12619:     my $total;
                   12620:     foreach my $val (@txts) { $total+=$val; }
                   12621:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12622:     return $total;
                   12623: }
                   12624: 
1.675     albertel 12625: sub digest {
                   12626:     my ($data)=@_;
                   12627:     my $digest=&Digest::MD5::md5($data);
                   12628:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12629:     my ($e,$f);
                   12630:     {
                   12631:         use integer;
                   12632:         $e=($a+$b);
                   12633:         $f=($c+$d);
                   12634:         if ($_64bit) {
                   12635:             $e=(($e<<32)>>32);
                   12636:             $f=(($f<<32)>>32);
                   12637:         }
                   12638:     }
                   12639:     if (wantarray) {
                   12640: 	return ($e,$f);
                   12641:     } else {
                   12642: 	my $g;
                   12643: 	{
                   12644: 	    use integer;
                   12645: 	    $g=($e+$f);
                   12646: 	    if ($_64bit) {
                   12647: 		$g=(($g<<32)>>32);
                   12648: 	    }
                   12649: 	}
                   12650: 	return $g;
                   12651:     }
                   12652: }
                   12653: 
1.368     albertel 12654: sub latest_rnd_algorithm_id {
1.675     albertel 12655:     return '64bit5';
1.366     albertel 12656: }
1.32      www      12657: 
1.503     albertel 12658: sub get_rand_alg {
                   12659:     my ($courseid)=@_;
1.790     albertel 12660:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12661:     if ($courseid) {
1.620     albertel 12662: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12663:     }
                   12664:     return &latest_rnd_algorithm_id();
                   12665: }
                   12666: 
1.562     albertel 12667: sub validCODE {
                   12668:     my ($CODE)=@_;
                   12669:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12670:     return 0;
                   12671: }
                   12672: 
1.491     albertel 12673: sub getCODE {
1.620     albertel 12674:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12675:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12676: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12677: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12678: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12679:     }
                   12680:     return undef;
                   12681: }
1.1133    foxr     12682: #
                   12683: #  Determines the random seed for a specific context:
                   12684: #
                   12685: # parameters:
                   12686: #   symb      - in course context the symb for the seed.
                   12687: #   course_id - The course id of the form domain_coursenum.
                   12688: #   domain    - Domain for the user.
                   12689: #   course    - Course for the user.
                   12690: #   cenv      - environment of the course.
                   12691: #
                   12692: # NOTE:
                   12693: #   All parameters are picked out of the environment if missing
                   12694: #   or not defined.
                   12695: #   If a symb cannot be determined the current time is used instead.
                   12696: #
                   12697: #  For a given well defined symb, courside, domain, username,
                   12698: #  and course environment, the seed is reproducible.
                   12699: #
1.31      www      12700: sub rndseed {
1.1133    foxr     12701:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12702:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12703:     if (!defined($symb)) {
1.366     albertel 12704: 	unless ($symb=$wsymb) { return time; }
                   12705:     }
1.1146    foxr     12706:     if (!defined $courseid) { 
                   12707: 	$courseid=$wcourseid; 
                   12708:     }
                   12709:     if (!defined $domain) { $domain=$wdomain; }
                   12710:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12711: 
                   12712:     my $which;
                   12713:     if (defined($cenv->{'rndseed'})) {
                   12714: 	$which = $cenv->{'rndseed'};
                   12715:     } else {
                   12716: 	$which =&get_rand_alg($courseid);
                   12717:     }
1.491     albertel 12718:     if (defined(&getCODE())) {
1.675     albertel 12719: 	if ($which eq '64bit5') {
                   12720: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12721: 	} elsif ($which eq '64bit4') {
1.575     albertel 12722: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12723: 	} else {
                   12724: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12725: 	}
1.675     albertel 12726:     } elsif ($which eq '64bit5') {
                   12727: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12728:     } elsif ($which eq '64bit4') {
                   12729: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12730:     } elsif ($which eq '64bit3') {
                   12731: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12732:     } elsif ($which eq '64bit2') {
                   12733: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12734:     } elsif ($which eq '64bit') {
                   12735: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12736:     }
                   12737:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12738: }
                   12739: 
                   12740: sub rndseed_32bit {
                   12741:     my ($symb,$courseid,$domain,$username)=@_;
                   12742:     {
                   12743: 	use integer;
                   12744: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12745: 	my $symbseed=numval($symb) << 22;
                   12746: 	my $namechck=unpack("%32C*",$username) << 17;
                   12747: 	my $nameseed=numval($username) << 12;
                   12748: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12749: 	my $courseseed=unpack("%32C*",$courseid);
                   12750: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12751: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12752: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12753: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12754: 	return $num;
                   12755:     }
                   12756: }
                   12757: 
                   12758: sub rndseed_64bit {
                   12759:     my ($symb,$courseid,$domain,$username)=@_;
                   12760:     {
                   12761: 	use integer;
                   12762: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12763: 	my $symbseed=numval($symb) << 10;
                   12764: 	my $namechck=unpack("%32S*",$username);
                   12765: 	
                   12766: 	my $nameseed=numval($username) << 21;
                   12767: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12768: 	my $courseseed=unpack("%32S*",$courseid);
                   12769: 	
                   12770: 	my $num1=$symbchck+$symbseed+$namechck;
                   12771: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12772: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12773: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12774: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12775: 	return "$num1,$num2";
1.155     albertel 12776:     }
1.366     albertel 12777: }
                   12778: 
1.443     albertel 12779: sub rndseed_64bit2 {
                   12780:     my ($symb,$courseid,$domain,$username)=@_;
                   12781:     {
                   12782: 	use integer;
                   12783: 	# strings need to be an even # of cahracters long, it it is odd the
                   12784:         # last characters gets thrown away
                   12785: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12786: 	my $symbseed=numval($symb) << 10;
                   12787: 	my $namechck=unpack("%32S*",$username.' ');
                   12788: 	
                   12789: 	my $nameseed=numval($username) << 21;
1.501     albertel 12790: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12791: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12792: 	
                   12793: 	my $num1=$symbchck+$symbseed+$namechck;
                   12794: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12795: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12796: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12797: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12798: 	return "$num1,$num2";
                   12799:     }
                   12800: }
                   12801: 
                   12802: sub rndseed_64bit3 {
                   12803:     my ($symb,$courseid,$domain,$username)=@_;
                   12804:     {
                   12805: 	use integer;
                   12806: 	# strings need to be an even # of cahracters long, it it is odd the
                   12807:         # last characters gets thrown away
                   12808: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12809: 	my $symbseed=numval2($symb) << 10;
                   12810: 	my $namechck=unpack("%32S*",$username.' ');
                   12811: 	
                   12812: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12813: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12814: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12815: 	
                   12816: 	my $num1=$symbchck+$symbseed+$namechck;
                   12817: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12818: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12819: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12820: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12821: 	
1.503     albertel 12822: 	return "$num1:$num2";
1.443     albertel 12823:     }
                   12824: }
                   12825: 
1.575     albertel 12826: sub rndseed_64bit4 {
                   12827:     my ($symb,$courseid,$domain,$username)=@_;
                   12828:     {
                   12829: 	use integer;
                   12830: 	# strings need to be an even # of cahracters long, it it is odd the
                   12831:         # last characters gets thrown away
                   12832: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12833: 	my $symbseed=numval3($symb) << 10;
                   12834: 	my $namechck=unpack("%32S*",$username.' ');
                   12835: 	
                   12836: 	my $nameseed=numval3($username) << 21;
                   12837: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12838: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12839: 	
                   12840: 	my $num1=$symbchck+$symbseed+$namechck;
                   12841: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12842: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12843: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12844: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12845: 	
1.575     albertel 12846: 	return "$num1:$num2";
                   12847:     }
                   12848: }
                   12849: 
1.675     albertel 12850: sub rndseed_64bit5 {
                   12851:     my ($symb,$courseid,$domain,$username)=@_;
                   12852:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12853:     return "$num1:$num2";
                   12854: }
                   12855: 
1.366     albertel 12856: sub rndseed_CODE_64bit {
                   12857:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12858:     {
1.366     albertel 12859: 	use integer;
1.443     albertel 12860: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12861: 	my $symbseed=numval2($symb);
1.491     albertel 12862: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12863: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12864: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12865: 	my $num1=$symbseed+$CODEchck;
                   12866: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12867: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12868: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12869: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12870: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12871: 	return "$num1:$num2";
1.366     albertel 12872:     }
                   12873: }
                   12874: 
1.575     albertel 12875: sub rndseed_CODE_64bit4 {
                   12876:     my ($symb,$courseid,$domain,$username)=@_;
                   12877:     {
                   12878: 	use integer;
                   12879: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12880: 	my $symbseed=numval3($symb);
                   12881: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12882: 	my $CODEseed=numval3(&getCODE());
                   12883: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12884: 	my $num1=$symbseed+$CODEchck;
                   12885: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12886: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12887: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12888: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12889: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12890: 	return "$num1:$num2";
                   12891:     }
                   12892: }
                   12893: 
1.675     albertel 12894: sub rndseed_CODE_64bit5 {
                   12895:     my ($symb,$courseid,$domain,$username)=@_;
                   12896:     my $code = &getCODE();
                   12897:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12898:     return "$num1:$num2";
                   12899: }
                   12900: 
1.366     albertel 12901: sub setup_random_from_rndseed {
                   12902:     my ($rndseed)=@_;
1.503     albertel 12903:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12904: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12905:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12906:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12907:         } else {
                   12908:             &Math::Random::random_set_seed($num1,$num2);
                   12909:         }
1.366     albertel 12910:     } else {
                   12911: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12912:     }
1.36      albertel 12913: }
                   12914: 
1.474     albertel 12915: sub latest_receipt_algorithm_id {
1.835     albertel 12916:     return 'receipt3';
1.474     albertel 12917: }
                   12918: 
1.480     www      12919: sub recunique {
                   12920:     my $fucourseid=shift;
                   12921:     my $unique;
1.835     albertel 12922:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12923: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12924: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12925:     } else {
                   12926: 	$unique=$perlvar{'lonReceipt'};
                   12927:     }
                   12928:     return unpack("%32C*",$unique);
                   12929: }
                   12930: 
                   12931: sub recprefix {
                   12932:     my $fucourseid=shift;
                   12933:     my $prefix;
1.835     albertel 12934:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12935: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12936: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12937:     } else {
                   12938: 	$prefix=$perlvar{'lonHostID'};
                   12939:     }
                   12940:     return unpack("%32C*",$prefix);
                   12941: }
                   12942: 
1.76      www      12943: sub ireceipt {
1.474     albertel 12944:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12945: 
                   12946:     my $return =&recprefix($fucourseid).'-';
                   12947: 
                   12948:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12949: 	$env{'request.state'} eq 'construct') {
                   12950: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12951: 	return $return;
                   12952:     }
                   12953: 
1.76      www      12954:     my $cuname=unpack("%32C*",$funame);
                   12955:     my $cudom=unpack("%32C*",$fudom);
                   12956:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12957:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12958:     my $cunique=&recunique($fucourseid);
1.474     albertel 12959:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12960:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12961: 
1.790     albertel 12962: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12963: 			       
                   12964: 	$return.= ($cunique%$cuname+
                   12965: 		   $cunique%$cudom+
                   12966: 		   $cusymb%$cuname+
                   12967: 		   $cusymb%$cudom+
                   12968: 		   $cucourseid%$cuname+
                   12969: 		   $cucourseid%$cudom+
                   12970: 		   $cpart%$cuname+
                   12971: 		   $cpart%$cudom);
                   12972:     } else {
                   12973: 	$return.= ($cunique%$cuname+
                   12974: 		   $cunique%$cudom+
                   12975: 		   $cusymb%$cuname+
                   12976: 		   $cusymb%$cudom+
                   12977: 		   $cucourseid%$cuname+
                   12978: 		   $cucourseid%$cudom);
                   12979:     }
                   12980:     return $return;
1.76      www      12981: }
                   12982: 
                   12983: sub receipt {
1.474     albertel 12984:     my ($part)=@_;
1.790     albertel 12985:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12986:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12987: }
1.260     ng       12988: 
1.790     albertel 12989: sub whichuser {
                   12990:     my ($passedsymb)=@_;
                   12991:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12992:     if (defined($env{'form.grade_symb'})) {
                   12993: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12994: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12995: 	if (!$allowed &&
                   12996: 	    exists($env{'request.course.sec'}) &&
                   12997: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12998: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12999: 			      '/'.$env{'request.course.sec'});
                   13000: 	}
                   13001: 	if ($allowed) {
                   13002: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13003: 	    $courseid=$tmp_courseid;
                   13004: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13005: 	    ($name)=&get_env_multiple('form.grade_username');
                   13006: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13007: 	}
                   13008:     }
                   13009:     if (!$passedsymb) {
                   13010: 	$symb=&symbread();
                   13011:     } else {
                   13012: 	$symb=$passedsymb;
                   13013:     }
                   13014:     $courseid=$env{'request.course.id'};
                   13015:     $domain=$env{'user.domain'};
                   13016:     $name=$env{'user.name'};
                   13017:     if ($name eq 'public' && $domain eq 'public') {
                   13018: 	if (!defined($env{'form.username'})) {
                   13019: 	    $env{'form.username'}.=time.rand(10000000);
                   13020: 	}
                   13021: 	$name.=$env{'form.username'};
                   13022:     }
                   13023:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13024: 
                   13025: }
                   13026: 
1.36      albertel 13027: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13028: # returns either the contents of the file or 
                   13029: # -1 if the file doesn't exist
1.481     raeburn  13030: #
                   13031: # if the target is a file that was uploaded via DOCS, 
                   13032: # a check will be made to see if a current copy exists on the local server,
                   13033: # if it does this will be served, otherwise a copy will be retrieved from
                   13034: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13035: # the local server.   
1.472     albertel 13036: 
1.36      albertel 13037: sub getfile {
1.538     albertel 13038:     my ($file) = @_;
1.609     banghart 13039:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13040:     &repcopy($file);
                   13041:     return &readfile($file);
                   13042: }
                   13043: 
                   13044: sub repcopy_userfile {
                   13045:     my ($file)=@_;
1.1142    raeburn  13046:     my $londocroot = $perlvar{'lonDocRoot'};
                   13047:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13048:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13049:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13050: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13051:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13052:     if (-e "$file") {
1.828     www      13053: # we already have a local copy, check it out
1.538     albertel 13054: 	my @fileinfo = stat($file);
1.828     www      13055: 	my $rtncode;
                   13056: 	my $info;
1.538     albertel 13057: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13058: 	if ($lwpresp ne 'ok') {
1.828     www      13059: # there is no such file anymore, even though we had a local copy
1.482     albertel 13060: 	    if ($rtncode eq '404') {
1.538     albertel 13061: 		unlink($file);
1.482     albertel 13062: 	    }
                   13063: 	    return -1;
                   13064: 	}
                   13065: 	if ($info < $fileinfo[9]) {
1.828     www      13066: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13067: 	    return 'ok';
1.828     www      13068: 	} else {
                   13069: # the file is outdated, get rid of it
                   13070: 	    unlink($file);
1.482     albertel 13071: 	}
1.828     www      13072:     }
                   13073: # one way or the other, at this point, we don't have the file
                   13074: # construct the correct path for the file
                   13075:     my @parts = ($cdom,$cnum); 
                   13076:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13077: 	push @parts, split(/\//,$1);
                   13078:     }
                   13079:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13080:     foreach my $part (@parts) {
                   13081: 	$path .= '/'.$part;
                   13082: 	if (!-e $path) {
                   13083: 	    mkdir($path,0770);
1.482     albertel 13084: 	}
                   13085:     }
1.828     www      13086: # now the path exists for sure
                   13087: # get a user agent
                   13088:     my $ua=new LWP::UserAgent;
                   13089:     my $transferfile=$file.'.in.transfer';
                   13090: # FIXME: this should flock
                   13091:     if (-e $transferfile) { return 'ok'; }
                   13092:     my $request;
                   13093:     $uri=~s/^\///;
1.980     raeburn  13094:     my $homeserver = &homeserver($cnum,$cdom);
                   13095:     my $protocol = $protocol{$homeserver};
                   13096:     $protocol = 'http' if ($protocol ne 'https');
                   13097:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      13098:     my $response=$ua->request($request,$transferfile);
                   13099: # did it work?
                   13100:     if ($response->is_error()) {
                   13101: 	unlink($transferfile);
                   13102: 	&logthis("Userfile repcopy failed for $uri");
                   13103: 	return -1;
                   13104:     }
                   13105: # worked, rename the transfer file
                   13106:     rename($transferfile,$file);
1.607     raeburn  13107:     return 'ok';
1.481     raeburn  13108: }
                   13109: 
1.517     albertel 13110: sub tokenwrapper {
                   13111:     my $uri=shift;
1.980     raeburn  13112:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13113:     $uri=~s|^/||;
1.620     albertel 13114:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13115:     my $token=$1;
1.552     albertel 13116:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13117:     if ($udom && $uname && $file) {
                   13118: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13119:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13120:         my $homeserver = &homeserver($uname,$udom);
                   13121:         my $protocol = $protocol{$homeserver};
                   13122:         $protocol = 'http' if ($protocol ne 'https');
                   13123:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13124:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13125:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13126:     } else {
                   13127:         return '/adm/notfound.html';
                   13128:     }
                   13129: }
                   13130: 
1.828     www      13131: # call with reqtype HEAD: get last modification time
                   13132: # call with reqtype GET: get the file contents
                   13133: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13134: #
1.481     raeburn  13135: sub getuploaded {
                   13136:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13137:     $uri=~s/^\///;
1.980     raeburn  13138:     my $homeserver = &homeserver($cnum,$cdom);
                   13139:     my $protocol = $protocol{$homeserver};
                   13140:     $protocol = 'http' if ($protocol ne 'https');
                   13141:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13142:     my $ua=new LWP::UserAgent;
                   13143:     my $request=new HTTP::Request($reqtype,$uri);
                   13144:     my $response=$ua->request($request);
                   13145:     $$rtncode = $response->code;
1.482     albertel 13146:     if (! $response->is_success()) {
                   13147: 	return 'failed';
                   13148:     }      
                   13149:     if ($reqtype eq 'HEAD') {
1.486     www      13150: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13151:     } elsif ($reqtype eq 'GET') {
                   13152: 	$$info = $response->content;
1.472     albertel 13153:     }
1.482     albertel 13154:     return 'ok';
1.36      albertel 13155: }
                   13156: 
1.481     raeburn  13157: sub readfile {
                   13158:     my $file = shift;
                   13159:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13160:     my $fh;
1.1172.2.96  raeburn  13161:     open($fh,"<",$file);
1.481     raeburn  13162:     my $a='';
1.800     albertel 13163:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13164:     return $a;
                   13165: }
                   13166: 
1.36      albertel 13167: sub filelocation {
1.590     banghart 13168:     my ($dir,$file) = @_;
                   13169:     my $location;
                   13170:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13171: 
                   13172:     if ($file =~ m-^/adm/-) {
                   13173: 	$file=~s-^/adm/wrapper/-/-;
                   13174: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13175:     }
1.882     albertel 13176: 
1.1139    www      13177:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13178:         $location = $file;
1.609     banghart 13179:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13180:         my ($udom,$uname,$filename)=
1.811     albertel 13181:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13182:         my $home=&homeserver($uname,$udom);
                   13183:         my $is_me=0;
                   13184:         my @ids=&current_machine_ids();
                   13185:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13186:         if ($is_me) {
1.1117    foxr     13187:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13188:         } else {
                   13189:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13190:   	      $udom.'/'.$uname.'/'.$filename;
                   13191:         }
1.882     albertel 13192:     } elsif ($file =~ m-^/adm/-) {
                   13193: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13194:     } else {
                   13195:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13196:         $file=~s:^/(res|priv)/:/:;
                   13197:         my $space=$1;
1.590     banghart 13198:         if ( !( $file =~ m:^/:) ) {
                   13199:             $location = $dir. '/'.$file;
                   13200:         } else {
1.1142    raeburn  13201:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13202:         }
1.59      albertel 13203:     }
1.590     banghart 13204:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13205:     while ($location=~m{/\.\./}) {
                   13206: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13207: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13208: 	} else {
                   13209: 	    $location=~ s{/\.\./}{/}g;
                   13210: 	}
                   13211:     } #remove dir/..
1.590     banghart 13212:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13213:     return $location;
1.46      www      13214: }
1.36      albertel 13215: 
1.46      www      13216: sub hreflocation {
                   13217:     my ($dir,$file)=@_;
1.980     raeburn  13218:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13219: 	$file=filelocation($dir,$file);
1.700     albertel 13220:     } elsif ($file=~m-^/adm/-) {
                   13221: 	$file=~s-^/adm/wrapper/-/-;
                   13222: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13223:     }
                   13224:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13225: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13226:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13227: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13228: 	        {/uploaded/$1/$2/}x;
1.46      www      13229:     }
1.913     albertel 13230:     if ($file=~ m{^/userfiles/}) {
                   13231: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13232:     }
1.462     albertel 13233:     return $file;
1.465     albertel 13234: }
                   13235: 
1.1139    www      13236: 
                   13237: 
                   13238: 
                   13239: 
1.465     albertel 13240: sub current_machine_domains {
1.853     albertel 13241:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13242: }
                   13243: 
                   13244: sub machine_domains {
                   13245:     my ($hostname) = @_;
1.465     albertel 13246:     my @domains;
1.838     albertel 13247:     my %hostname = &all_hostnames();
1.465     albertel 13248:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13249: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13250: 	if ($hostname eq $name) {
1.844     albertel 13251: 	    push(@domains,&host_domain($id));
1.465     albertel 13252: 	}
                   13253:     }
                   13254:     return @domains;
                   13255: }
                   13256: 
                   13257: sub current_machine_ids {
1.853     albertel 13258:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13259: }
                   13260: 
                   13261: sub machine_ids {
                   13262:     my ($hostname) = @_;
                   13263:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13264:     my @ids;
1.888     albertel 13265:     my %name_to_host = &all_names();
1.889     albertel 13266:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13267: 	return @{ $name_to_host{$hostname} };
                   13268:     }
                   13269:     return;
1.31      www      13270: }
                   13271: 
1.824     raeburn  13272: sub additional_machine_domains {
                   13273:     my @domains;
1.1172.2.96  raeburn  13274:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13275:     while( my $line = <$fh>) {
                   13276:         $line =~ s/\s//g;
                   13277:         push(@domains,$line);
                   13278:     }
                   13279:     return @domains;
                   13280: }
                   13281: 
                   13282: sub default_login_domain {
                   13283:     my $domain = $perlvar{'lonDefDomain'};
                   13284:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13285:     foreach my $posdom (&current_machine_domains(),
                   13286:                         &additional_machine_domains()) {
                   13287:         if (lc($posdom) eq lc($testdomain)) {
                   13288:             $domain=$posdom;
                   13289:             last;
                   13290:         }
                   13291:     }
                   13292:     return $domain;
                   13293: }
                   13294: 
1.1172.2.106  raeburn  13295: sub shared_institution {
                   13296:     my ($dom) = @_;
                   13297:     my $same_intdom;
                   13298:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13299:     if ($hostintdom ne '') {
                   13300:         my %iphost = &get_iphost();
                   13301:         my $primary_id = &domain($dom,'primary');
                   13302:         my $primary_ip = &get_host_ip($primary_id);
                   13303:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13304:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13305:                 my $intdom = &internet_dom($id);
                   13306:                 if ($intdom eq $hostintdom) {
                   13307:                     $same_intdom = 1;
                   13308:                     last;
                   13309:                 }
                   13310:             }
                   13311:         }
                   13312:     }
                   13313:     return $same_intdom;
                   13314: }
                   13315: 
1.31      www      13316: # ------------------------------------------------------------- Declutters URLs
                   13317: 
                   13318: sub declutter {
                   13319:     my $thisfn=shift;
1.569     albertel 13320:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13321:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13322:         $thisfn=~s{^/home/httpd/html}{};
                   13323:     }
1.31      www      13324:     $thisfn=~s/^\///;
1.697     albertel 13325:     $thisfn=~s|^adm/wrapper/||;
                   13326:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13327:     $thisfn=~s/^res\///;
1.1172    bisitz   13328:     $thisfn=~s/^priv\///;
1.1032    raeburn  13329:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13330:         $thisfn=~s/\?.+$//;
                   13331:     }
1.268     www      13332:     return $thisfn;
                   13333: }
                   13334: 
                   13335: # ------------------------------------------------------------- Clutter up URLs
                   13336: 
                   13337: sub clutter {
                   13338:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13339:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13340: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13341:        $thisfn='/res'.$thisfn; 
                   13342:     }
1.1031    raeburn  13343:     if ($thisfn !~m|^/adm|) {
                   13344: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13345: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13346: 	} else {
                   13347: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13348: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13349: 	    if ($embstyle eq 'ssi'
                   13350: 		|| ($embstyle eq 'hdn')
                   13351: 		|| ($embstyle eq 'rat')
                   13352: 		|| ($embstyle eq 'prv')
                   13353: 		|| ($embstyle eq 'ign')) {
                   13354: 		#do nothing with these
                   13355: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13356: 		|| ($embstyle eq 'emb')
                   13357: 		|| ($embstyle eq 'wrp')) {
                   13358: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13359: 	    } elsif ($embstyle eq 'unk'
                   13360: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13361: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13362: 	    } else {
1.718     www      13363: #		&logthis("Got a blank emb style");
1.695     albertel 13364: 	    }
1.694     albertel 13365: 	}
1.1172.2.118.  .1(raebu 13366:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13367:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13368:     }
1.31      www      13369:     return $thisfn;
1.12      www      13370: }
                   13371: 
1.787     albertel 13372: sub clutter_with_no_wrapper {
                   13373:     my $uri = &clutter(shift);
                   13374:     if ($uri =~ m-^/adm/-) {
                   13375: 	$uri =~ s-^/adm/wrapper/-/-;
                   13376: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13377:     }
                   13378:     return $uri;
                   13379: }
                   13380: 
1.557     albertel 13381: sub freeze_escape {
                   13382:     my ($value)=@_;
                   13383:     if (ref($value)) {
                   13384: 	$value=&nfreeze($value);
                   13385: 	return '__FROZEN__'.&escape($value);
                   13386:     }
                   13387:     return &escape($value);
                   13388: }
                   13389: 
1.11      www      13390: 
1.557     albertel 13391: sub thaw_unescape {
                   13392:     my ($value)=@_;
                   13393:     if ($value =~ /^__FROZEN__/) {
                   13394: 	substr($value,0,10,undef);
                   13395: 	$value=&unescape($value);
                   13396: 	return &thaw($value);
                   13397:     }
                   13398:     return &unescape($value);
                   13399: }
                   13400: 
1.436     albertel 13401: sub correct_line_ends {
                   13402:     my ($result)=@_;
                   13403:     $$result =~s/\r\n/\n/mg;
                   13404:     $$result =~s/\r/\n/mg;
1.415     albertel 13405: }
1.1       albertel 13406: # ================================================================ Main Program
                   13407: 
1.184     www      13408: sub goodbye {
1.204     albertel 13409:    &logthis("Starting Shut down");
1.443     albertel 13410: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13411:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13412: #converted
1.599     albertel 13413: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13414:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13415: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13416: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13417: #1.1 only
1.870     albertel 13418: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13419: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13420: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13421: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13422:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13423:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13424:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13425:    &flushcourselogs();
                   13426:    &logthis("Shutting down");
                   13427: }
                   13428: 
1.852     albertel 13429: sub get_dns {
1.1172.2.17  raeburn  13430:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13431:     if (!$ignore_cache) {
                   13432: 	my ($content,$cached)=
                   13433: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13434: 	if ($cached) {
1.1172.2.17  raeburn  13435: 	    &$func($content,$hashref);
1.869     albertel 13436: 	    return;
                   13437: 	}
                   13438:     }
                   13439: 
                   13440:     my %alldns;
1.1172.2.96  raeburn  13441:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13442:         foreach my $dns (<$config>) {
                   13443: 	    next if ($dns !~ /^\^(\S*)/x);
                   13444:             my $line = $1;
                   13445:             my ($host,$protocol) = split(/:/,$line);
                   13446:             if ($protocol ne 'https') {
                   13447:                 $protocol = 'http';
                   13448:             }
                   13449: 	    $alldns{$host} = $protocol;
1.979     raeburn  13450:         }
1.1172.2.96  raeburn  13451:         close($config);
1.869     albertel 13452:     }
                   13453:     while (%alldns) {
1.1172.2.52  raeburn  13454: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13455: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13456:         $ua->timeout(30);
1.979     raeburn  13457: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13458: 	my $response=$ua->request($request);
1.979     raeburn  13459:         delete($alldns{$dns});
1.852     albertel 13460: 	next if ($response->is_error());
                   13461: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13462:         unless ($nocache) {
1.1172.2.23  raeburn  13463: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13464:         }
                   13465: 	&$func(\@content,$hashref);
1.869     albertel 13466: 	return;
1.852     albertel 13467:     }
1.871     albertel 13468:     my $which = (split('/',$url))[3];
                   13469:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13470:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13471:         my @content = <$config>;
                   13472:         &$func(\@content,$hashref);
                   13473:     }
1.1172.2.17  raeburn  13474:     return;
                   13475: }
                   13476: 
                   13477: # ------------------------------------------------------Get DNS checksums file
                   13478: sub parse_dns_checksums_tab {
                   13479:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13480:     my $lonhost = $perlvar{'lonHostID'};
                   13481:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13482:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13483:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13484:     my $webconfdir = '/etc/httpd/conf';
                   13485:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13486:         $webconfdir = '/etc/apache2';
                   13487:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13488:         if ($1 >= 10) {
                   13489:             $webconfdir = '/etc/apache2';
                   13490:         }
                   13491:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13492:         if ($1 >= 10.0) {
                   13493:             $webconfdir = '/etc/apache2';
                   13494:         }
                   13495:     }
1.1172.2.17  raeburn  13496:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13497:     my (%chksum,%revnum);
                   13498:     if (ref($lines) eq 'ARRAY') {
                   13499:         chomp(@{$lines});
1.1172.2.34  raeburn  13500:         my $version = shift(@{$lines});
                   13501:         if ($version eq $release) {
1.1172.2.17  raeburn  13502:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13503:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13504:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13505:                     if ($webconfdir eq '/etc/apache2') {
                   13506:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13507:                     }
                   13508:                 }
1.1172.2.34  raeburn  13509:                 $chksum{$file} = $shasum;
                   13510:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13511:             }
                   13512:             if (ref($hashref) eq 'HASH') {
                   13513:                 %{$hashref} = (
                   13514:                                 sums     => \%chksum,
                   13515:                                 versions => \%revnum,
                   13516:                               );
                   13517:             }
                   13518:         }
                   13519:     }
1.869     albertel 13520:     return;
1.852     albertel 13521: }
1.1172.2.17  raeburn  13522: 
                   13523: sub fetch_dns_checksums {
                   13524:     my %checksums;
1.1172.2.34  raeburn  13525:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13526:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13527:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13528:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13529:              \%checksums);
                   13530:     return \%checksums;
                   13531: }
                   13532: 
1.327     albertel 13533: # ------------------------------------------------------------ Read domain file
                   13534: {
1.852     albertel 13535:     my $loaded;
1.846     albertel 13536:     my %domain;
                   13537: 
1.852     albertel 13538:     sub parse_domain_tab {
                   13539: 	my ($lines) = @_;
                   13540: 	foreach my $line (@$lines) {
                   13541: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13542: 
1.846     albertel 13543: 	    chomp($line);
1.852     albertel 13544: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13545: 	    my %this_domain;
                   13546: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13547: 			       'lang_def', 'city', 'longi', 'lati',
                   13548: 			       'primary') {
                   13549: 		$this_domain{$field} = shift(@elements);
                   13550: 	    }
                   13551: 	    $domain{$name} = \%this_domain;
1.852     albertel 13552: 	}
                   13553:     }
1.864     albertel 13554: 
                   13555:     sub reset_domain_info {
                   13556: 	undef($loaded);
                   13557: 	undef(%domain);
                   13558:     }
                   13559: 
1.852     albertel 13560:     sub load_domain_tab {
1.1172.2.70  raeburn  13561: 	my ($ignore_cache,$nocache) = @_;
                   13562: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13563: 	my $fh;
1.1172.2.96  raeburn  13564: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13565: 	    my @lines = <$fh>;
                   13566: 	    &parse_domain_tab(\@lines);
1.448     albertel 13567: 	}
1.852     albertel 13568: 	close($fh);
                   13569: 	$loaded = 1;
1.327     albertel 13570:     }
1.846     albertel 13571: 
                   13572:     sub domain {
1.852     albertel 13573: 	&load_domain_tab() if (!$loaded);
                   13574: 
1.846     albertel 13575: 	my ($name,$what) = @_;
                   13576: 	return if ( !exists($domain{$name}) );
                   13577: 
                   13578: 	if (!$what) {
                   13579: 	    return $domain{$name}{'description'};
                   13580: 	}
                   13581: 	return $domain{$name}{$what};
                   13582:     }
1.974     raeburn  13583: 
                   13584:     sub domain_info {
                   13585:         &load_domain_tab() if (!$loaded);
                   13586:         return %domain;
                   13587:     }
                   13588: 
1.327     albertel 13589: }
                   13590: 
                   13591: 
1.1       albertel 13592: # ------------------------------------------------------------- Read hosts file
                   13593: {
1.838     albertel 13594:     my %hostname;
1.844     albertel 13595:     my %hostdom;
1.845     albertel 13596:     my %libserv;
1.852     albertel 13597:     my $loaded;
1.888     albertel 13598:     my %name_to_host;
1.1074    raeburn  13599:     my %internetdom;
1.1107    raeburn  13600:     my %LC_dns_serv;
1.852     albertel 13601: 
                   13602:     sub parse_hosts_tab {
                   13603: 	my ($file) = @_;
                   13604: 	foreach my $configline (@$file) {
                   13605: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13606:             chomp($configline);
                   13607: 	    if ($configline =~ /^\^/) {
                   13608:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13609:                     $LC_dns_serv{$1} = 1;
                   13610:                 }
                   13611:                 next;
                   13612:             }
1.1074    raeburn  13613: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13614: 	    $name=~s/\s//g;
                   13615: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13616:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13617:                     my $curr = $hostname{$id};
                   13618:                     my $skip;
                   13619:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13620:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13621:                             $skip = 1;
                   13622:                         } else {
                   13623:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13624:                         }
                   13625:                     }
                   13626:                     unless ($skip) {
                   13627:                         push(@{$name_to_host{$name}},$id);
                   13628:                     }
                   13629:                 } else {
                   13630:                     push(@{$name_to_host{$name}},$id);
                   13631:                 }
1.852     albertel 13632: 		$hostname{$id}=$name;
                   13633: 		$hostdom{$id}=$domain;
                   13634: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13635:                 if (defined($protocol)) {
                   13636:                     if ($protocol eq 'https') {
                   13637:                         $protocol{$id} = $protocol;
                   13638:                     } else {
                   13639:                         $protocol{$id} = 'http'; 
                   13640:                     }
1.968     raeburn  13641:                 } else {
1.969     raeburn  13642:                     $protocol{$id} = 'http';
1.968     raeburn  13643:                 }
1.1074    raeburn  13644:                 if (defined($intdom)) {
                   13645:                     $internetdom{$id} = $intdom;
                   13646:                 }
1.852     albertel 13647: 	    }
                   13648: 	}
                   13649:     }
1.864     albertel 13650:     
                   13651:     sub reset_hosts_info {
1.897     albertel 13652: 	&purge_remembered();
1.864     albertel 13653: 	&reset_domain_info();
                   13654: 	&reset_hosts_ip_info();
1.892     albertel 13655: 	undef(%name_to_host);
1.864     albertel 13656: 	undef(%hostname);
                   13657: 	undef(%hostdom);
                   13658: 	undef(%libserv);
                   13659: 	undef($loaded);
                   13660:     }
1.1       albertel 13661: 
1.852     albertel 13662:     sub load_hosts_tab {
1.1172.2.70  raeburn  13663: 	my ($ignore_cache,$nocache) = @_;
                   13664: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13665: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13666: 	my @config = <$config>;
                   13667: 	&parse_hosts_tab(\@config);
                   13668: 	close($config);
                   13669: 	$loaded=1;
1.1       albertel 13670:     }
1.852     albertel 13671: 
1.838     albertel 13672:     sub hostname {
1.852     albertel 13673: 	&load_hosts_tab() if (!$loaded);
                   13674: 
1.838     albertel 13675: 	my ($lonid) = @_;
                   13676: 	return $hostname{$lonid};
                   13677:     }
1.845     albertel 13678: 
1.838     albertel 13679:     sub all_hostnames {
1.852     albertel 13680: 	&load_hosts_tab() if (!$loaded);
                   13681: 
1.838     albertel 13682: 	return %hostname;
                   13683:     }
1.845     albertel 13684: 
1.888     albertel 13685:     sub all_names {
1.1172.2.70  raeburn  13686:         my ($ignore_cache,$nocache) = @_;
                   13687: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13688: 
                   13689: 	return %name_to_host;
                   13690:     }
                   13691: 
1.974     raeburn  13692:     sub all_host_domain {
                   13693:         &load_hosts_tab() if (!$loaded);
                   13694:         return %hostdom;
                   13695:     }
                   13696: 
1.845     albertel 13697:     sub is_library {
1.852     albertel 13698: 	&load_hosts_tab() if (!$loaded);
                   13699: 
1.845     albertel 13700: 	return exists($libserv{$_[0]});
                   13701:     }
                   13702: 
                   13703:     sub all_library {
1.852     albertel 13704: 	&load_hosts_tab() if (!$loaded);
                   13705: 
1.845     albertel 13706: 	return %libserv;
                   13707:     }
                   13708: 
1.1062    droeschl 13709:     sub unique_library {
                   13710: 	#2x reverse removes all hostnames that appear more than once
                   13711:         my %unique = reverse &all_library();
                   13712:         return reverse %unique;
                   13713:     }
                   13714: 
1.841     albertel 13715:     sub get_servers {
1.852     albertel 13716: 	&load_hosts_tab() if (!$loaded);
                   13717: 
1.841     albertel 13718: 	my ($domain,$type) = @_;
                   13719: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13720: 	                                          : %hostname;
                   13721: 	my %result;
1.842     albertel 13722: 	if (ref($domain) eq 'ARRAY') {
                   13723: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13724: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13725: 		    $result{$host} = $hostname;
                   13726: 		}
                   13727: 	    }
                   13728: 	} else {
                   13729: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13730: 		if ($hostdom{$host} eq $domain) {
                   13731: 		    $result{$host} = $hostname;
                   13732: 		}
1.841     albertel 13733: 	    }
                   13734: 	}
                   13735: 	return %result;
                   13736:     }
1.845     albertel 13737: 
1.1062    droeschl 13738:     sub get_unique_servers {
                   13739:         my %unique = reverse &get_servers(@_);
                   13740: 	return reverse %unique;
                   13741:     }
                   13742: 
1.844     albertel 13743:     sub host_domain {
1.852     albertel 13744: 	&load_hosts_tab() if (!$loaded);
                   13745: 
1.844     albertel 13746: 	my ($lonid) = @_;
                   13747: 	return $hostdom{$lonid};
                   13748:     }
                   13749: 
1.841     albertel 13750:     sub all_domains {
1.852     albertel 13751: 	&load_hosts_tab() if (!$loaded);
                   13752: 
1.841     albertel 13753: 	my %seen;
                   13754: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13755: 	return @uniq;
                   13756:     }
1.1074    raeburn  13757: 
                   13758:     sub internet_dom {
                   13759:         &load_hosts_tab() if (!$loaded);
                   13760: 
                   13761:         my ($lonid) = @_;
                   13762:         return $internetdom{$lonid};
                   13763:     }
1.1107    raeburn  13764: 
                   13765:     sub is_LC_dns {
                   13766:         &load_hosts_tab() if (!$loaded);
                   13767: 
                   13768:         my ($hostname) = @_;
                   13769:         return exists($LC_dns_serv{$hostname});
                   13770:     }
                   13771: 
1.1       albertel 13772: }
                   13773: 
1.847     albertel 13774: { 
                   13775:     my %iphost;
1.856     albertel 13776:     my %name_to_ip;
                   13777:     my %lonid_to_ip;
1.869     albertel 13778: 
1.847     albertel 13779:     sub get_hosts_from_ip {
                   13780: 	my ($ip) = @_;
                   13781: 	my %iphosts = &get_iphost();
                   13782: 	if (ref($iphosts{$ip})) {
                   13783: 	    return @{$iphosts{$ip}};
                   13784: 	}
                   13785: 	return;
1.839     albertel 13786:     }
1.864     albertel 13787:     
                   13788:     sub reset_hosts_ip_info {
                   13789: 	undef(%iphost);
                   13790: 	undef(%name_to_ip);
                   13791: 	undef(%lonid_to_ip);
                   13792:     }
1.856     albertel 13793: 
                   13794:     sub get_host_ip {
                   13795: 	my ($lonid) = @_;
                   13796: 	if (exists($lonid_to_ip{$lonid})) {
                   13797: 	    return $lonid_to_ip{$lonid};
                   13798: 	}
                   13799: 	my $name=&hostname($lonid);
                   13800:    	my $ip = gethostbyname($name);
                   13801: 	return if (!$ip || length($ip) ne 4);
                   13802: 	$ip=inet_ntoa($ip);
                   13803: 	$name_to_ip{$name}   = $ip;
                   13804: 	$lonid_to_ip{$lonid} = $ip;
                   13805: 	return $ip;
                   13806:     }
1.847     albertel 13807:     
                   13808:     sub get_iphost {
1.1172.2.70  raeburn  13809: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13810: 
1.869     albertel 13811: 	if (!$ignore_cache) {
                   13812: 	    if (%iphost) {
                   13813: 		return %iphost;
                   13814: 	    }
                   13815: 	    my ($ip_info,$cached)=
                   13816: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13817: 	    if ($cached) {
                   13818: 		%iphost      = %{$ip_info->[0]};
                   13819: 		%name_to_ip  = %{$ip_info->[1]};
                   13820: 		%lonid_to_ip = %{$ip_info->[2]};
                   13821: 		return %iphost;
                   13822: 	    }
                   13823: 	}
1.894     albertel 13824: 
                   13825: 	# get yesterday's info for fallback
                   13826: 	my %old_name_to_ip;
                   13827: 	my ($ip_info,$cached)=
                   13828: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13829: 	if ($cached) {
                   13830: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13831: 	}
                   13832: 
1.1172.2.70  raeburn  13833: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13834: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13835: 	    my $ip;
                   13836: 	    if (!exists($name_to_ip{$name})) {
                   13837: 		$ip = gethostbyname($name);
                   13838: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13839: 		    if (defined($old_name_to_ip{$name})) {
                   13840: 			$ip = $old_name_to_ip{$name};
                   13841: 			&logthis("Can't find $name defaulting to old $ip");
                   13842: 		    } else {
                   13843: 			&logthis("Name $name no IP found");
                   13844: 			next;
                   13845: 		    }
                   13846: 		} else {
                   13847: 		    $ip=inet_ntoa($ip);
1.847     albertel 13848: 		}
                   13849: 		$name_to_ip{$name} = $ip;
                   13850: 	    } else {
                   13851: 		$ip = $name_to_ip{$name};
1.653     albertel 13852: 	    }
1.888     albertel 13853: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13854: 		$lonid_to_ip{$id} = $ip;
                   13855: 	    }
                   13856: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13857: 	}
1.1172.2.70  raeburn  13858:         unless ($nocache) {
                   13859: 	    &do_cache_new('iphost','iphost',
                   13860: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13861: 		          48*60*60);
                   13862:         }
1.869     albertel 13863: 
1.847     albertel 13864: 	return %iphost;
1.598     albertel 13865:     }
                   13866: 
1.992     raeburn  13867:     #
                   13868:     #  Given a DNS returns the loncapa host name for that DNS 
                   13869:     # 
                   13870:     sub host_from_dns {
                   13871:         my ($dns) = @_;
                   13872:         my @hosts;
                   13873:         my $ip;
                   13874: 
1.993     raeburn  13875:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13876:             $ip = $name_to_ip{$dns};
                   13877:         }
                   13878:         if (!$ip) {
                   13879:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13880:             if (length($ip) == 4) { 
                   13881: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13882:             }
                   13883:         }
                   13884:         if ($ip) {
                   13885: 	    @hosts = get_hosts_from_ip($ip);
                   13886: 	    return $hosts[0];
                   13887:         }
                   13888:         return undef;
1.986     foxr     13889:     }
1.992     raeburn  13890: 
1.1074    raeburn  13891:     sub get_internet_names {
                   13892:         my ($lonid) = @_;
                   13893:         return if ($lonid eq '');
                   13894:         my ($idnref,$cached)=
                   13895:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13896:         if ($cached) {
                   13897:             return $idnref;
                   13898:         }
                   13899:         my $ip = &get_host_ip($lonid);
                   13900:         my @hosts = &get_hosts_from_ip($ip);
                   13901:         my %iphost = &get_iphost();
                   13902:         my (@idns,%seen);
                   13903:         foreach my $id (@hosts) {
                   13904:             my $dom = &host_domain($id);
                   13905:             my $prim_id = &domain($dom,'primary');
                   13906:             my $prim_ip = &get_host_ip($prim_id);
                   13907:             next if ($seen{$prim_ip});
                   13908:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13909:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13910:                     my $intdom = &internet_dom($id);
                   13911:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13912:                         push(@idns,$intdom);
                   13913:                     }
                   13914:                 }
                   13915:             }
                   13916:             $seen{$prim_ip} = 1;
                   13917:         }
1.1172.2.23  raeburn  13918:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13919:     }
                   13920: 
1.986     foxr     13921: }
                   13922: 
1.1079    raeburn  13923: sub all_loncaparevs {
1.1172.2.39  raeburn  13924:     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  13925: }
                   13926: 
1.1172.2.27  raeburn  13927: # ------------------------------------------------------- Read loncaparev table
                   13928: {
                   13929:     sub load_loncaparevs {
                   13930:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13931:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13932:                 while (my $configline=<$config>) {
                   13933:                     chomp($configline);
                   13934:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13935:                     $loncaparevs{$hostid}=$loncaparev;
                   13936:                 }
                   13937:                 close($config);
                   13938:             }
                   13939:         }
                   13940:     }
                   13941: }
                   13942: 
                   13943: # ----------------------------------------------------- Read serverhostID table
                   13944: {
                   13945:     sub load_serverhomeIDs {
                   13946:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13947:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13948:                 while (my $configline=<$config>) {
                   13949:                     chomp($configline);
                   13950:                     my ($name,$id)=split(/:/,$configline);
                   13951:                     $serverhomeIDs{$name}=$id;
                   13952:                 }
                   13953:                 close($config);
                   13954:             }
                   13955:         }
                   13956:     }
                   13957: }
                   13958: 
                   13959: 
1.862     albertel 13960: BEGIN {
                   13961: 
                   13962: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13963:     unless ($readit) {
                   13964: {
                   13965:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13966:     %perlvar = (%perlvar,%{$configvars});
                   13967: }
                   13968: 
                   13969: 
1.1       albertel 13970: # ------------------------------------------------------ Read spare server file
                   13971: {
1.1172.2.96  raeburn  13972:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13973: 
                   13974:     while (my $configline=<$config>) {
                   13975:        chomp($configline);
1.284     matthew  13976:        if ($configline) {
1.784     albertel 13977: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13978: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13979: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13980:        }
                   13981:     }
1.448     albertel 13982:     close($config);
1.1       albertel 13983: }
1.11      www      13984: # ------------------------------------------------------------ Read permissions
                   13985: {
1.1172.2.96  raeburn  13986:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13987: 
                   13988:     while (my $configline=<$config>) {
1.448     albertel 13989: 	chomp($configline);
                   13990: 	if ($configline) {
                   13991: 	    my ($role,$perm)=split(/ /,$configline);
                   13992: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13993: 	}
1.11      www      13994:     }
1.448     albertel 13995:     close($config);
1.11      www      13996: }
                   13997: 
                   13998: # -------------------------------------------- Read plain texts for permissions
                   13999: {
1.1172.2.96  raeburn  14000:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14001: 
                   14002:     while (my $configline=<$config>) {
1.448     albertel 14003: 	chomp($configline);
                   14004: 	if ($configline) {
1.742     raeburn  14005: 	    my ($short,@plain)=split(/:/,$configline);
                   14006:             %{$prp{$short}} = ();
                   14007: 	    if (@plain > 0) {
                   14008:                 $prp{$short}{'std'} = $plain[0];
                   14009:                 for (my $i=1; $i<@plain; $i++) {
                   14010:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14011:                 }
                   14012:             }
1.448     albertel 14013: 	}
1.135     www      14014:     }
1.448     albertel 14015:     close($config);
1.135     www      14016: }
                   14017: 
                   14018: # ---------------------------------------------------------- Read package table
                   14019: {
1.1172.2.96  raeburn  14020:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14021: 
                   14022:     while (my $configline=<$config>) {
1.483     albertel 14023: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14024: 	chomp($configline);
                   14025: 	my ($short,$plain)=split(/:/,$configline);
                   14026: 	my ($pack,$name)=split(/\&/,$short);
                   14027: 	if ($plain ne '') {
                   14028: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14029: 	    $packagetab{$short}=$plain; 
                   14030: 	}
1.11      www      14031:     }
1.448     albertel 14032:     close($config);
1.329     matthew  14033: }
                   14034: 
1.1172.2.27  raeburn  14035: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14036: 
1.1172.2.27  raeburn  14037: &load_loncaparevs();
                   14038: 
                   14039: # ------------------------------------------------------- Read serverhostID table
                   14040: 
                   14041: &load_serverhomeIDs();
1.1074    raeburn  14042: 
1.1172.2.27  raeburn  14043: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14044: {
                   14045:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14046:     if (-e $file) {
                   14047:         my $parser = HTML::LCParser->new($file);
                   14048:         while (my $token = $parser->get_token()) {
                   14049:             if ($token->[0] eq 'S') {
                   14050:                 my $item = $token->[1];
                   14051:                 my $name = $token->[2]{'name'};
                   14052:                 my $value = $token->[2]{'value'};
                   14053:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14054:                     my $release = $parser->get_text();
                   14055:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14056:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14057:                 }
                   14058:             }
                   14059:         }
                   14060:     }
1.1073    raeburn  14061: }
                   14062: 
1.1138    raeburn  14063: # ---------------------------------------------------------- Read managers table
                   14064: {
                   14065:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14066:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14067:             while (my $configline=<$config>) {
                   14068:                 chomp($configline);
                   14069:                 next if ($configline =~ /^\#/);
                   14070:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14071:                     $managerstab{$configline} = 1;
                   14072:                 }
                   14073:             }
                   14074:             close($config);
                   14075:         }
                   14076:     }
                   14077: }
                   14078: 
1.329     matthew  14079: # ------------- set up temporary directory
                   14080: {
1.1117    foxr     14081:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14082: 
1.11      www      14083: }
                   14084: 
1.1172.2.104  raeburn  14085: # ------------- set default texengine (domain default overrides this)
                   14086: {
                   14087:     $deftex = LONCAPA::texengine();
                   14088: }
                   14089: 
1.1172.2.114  raeburn  14090: # ------------- set default minimum length for passwords for internal auth users
                   14091: {
                   14092:     $passwdmin = LONCAPA::passwd_min();
                   14093: }
                   14094: 
1.794     albertel 14095: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14096: 				'compress_threshold'=> 20_000,
                   14097:  			        });
1.185     www      14098: 
1.281     www      14099: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14100: $dumpcount=0;
1.958     www      14101: $locknum=0;
1.22      www      14102: 
1.163     harris41 14103: &logtouch();
1.672     albertel 14104: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14105: $readit=1;
1.564     albertel 14106:     {
                   14107: 	use integer;
                   14108: 	my $test=(2**32)+1;
1.568     albertel 14109: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14110: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14111:     }
1.195     www      14112: }
1.1       albertel 14113: }
1.179     www      14114: 
1.1       albertel 14115: 1;
1.191     harris41 14116: __END__
                   14117: 
1.243     albertel 14118: =pod
                   14119: 
1.191     harris41 14120: =head1 NAME
                   14121: 
1.243     albertel 14122: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14123: 
                   14124: =head1 SYNOPSIS
                   14125: 
1.243     albertel 14126: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14127: 
                   14128:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14129: 
1.243     albertel 14130: Common parameters:
                   14131: 
                   14132: =over 4
                   14133: 
                   14134: =item *
                   14135: 
                   14136: $uname : an internal username (if $cname expecting a course Id specifically)
                   14137: 
                   14138: =item *
                   14139: 
                   14140: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14141: 
                   14142: =item *
                   14143: 
                   14144: $symb : a resource instance identifier
                   14145: 
                   14146: =item *
                   14147: 
                   14148: $namespace : the name of a .db file that contains the data needed or
                   14149: being set.
                   14150: 
                   14151: =back
                   14152: 
1.394     bowersj2 14153: =head1 OVERVIEW
1.191     harris41 14154: 
1.394     bowersj2 14155: lonnet provides subroutines which interact with the
                   14156: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14157: about classes, users, and resources.
1.243     albertel 14158: 
                   14159: For many of these objects you can also use this to store data about
                   14160: them or modify them in various ways.
1.191     harris41 14161: 
1.394     bowersj2 14162: =head2 Symbs
1.191     harris41 14163: 
1.394     bowersj2 14164: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14165: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14166: map, the resource number of the resource in the map, and the URL of
                   14167: the resource itself. The latter is somewhat redundant, but might help
                   14168: if maps change.
                   14169: 
                   14170: An example is
                   14171: 
                   14172:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14173: 
                   14174: The respective map entry is
                   14175: 
                   14176:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14177:   title="Problem 2">
                   14178:  </resource>
                   14179: 
                   14180: Symbs are used by the random number generator, as well as to store and
                   14181: restore data specific to a certain instance of for example a problem.
                   14182: 
                   14183: =head2 Storing And Retrieving Data
                   14184: 
                   14185: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14186: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14187: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14188: is is the non-critical message twin of cstore. These functions are for
                   14189: handlers to store a perl hash to a user's permanent data space in an
                   14190: easy manner, and to retrieve it again on another call. It is expected
                   14191: that a handler would use this once at the beginning to retrieve data,
                   14192: and then again once at the end to send only the new data back.
                   14193: 
                   14194: The data is stored in the user's data directory on the user's
                   14195: homeserver under the ID of the course.
                   14196: 
                   14197: The hash that is returned by restore will have all of the previous
                   14198: value for all of the elements of the hash.
                   14199: 
                   14200: Example:
                   14201: 
                   14202:  #creating a hash
                   14203:  my %hash;
                   14204:  $hash{'foo'}='bar';
                   14205: 
                   14206:  #storing it
                   14207:  &Apache::lonnet::cstore(\%hash);
                   14208: 
                   14209:  #changing a value
                   14210:  $hash{'foo'}='notbar';
                   14211: 
                   14212:  #adding a new value
                   14213:  $hash{'bar'}='foo';
                   14214:  &Apache::lonnet::cstore(\%hash);
                   14215: 
                   14216:  #retrieving the hash
                   14217:  my %history=&Apache::lonnet::restore();
                   14218: 
                   14219:  #print the hash
                   14220:  foreach my $key (sort(keys(%history))) {
                   14221:    print("\%history{$key} = $history{$key}");
                   14222:  }
                   14223: 
                   14224: Will print out:
1.191     harris41 14225: 
1.394     bowersj2 14226:  %history{1:foo} = bar
                   14227:  %history{1:keys} = foo:timestamp
                   14228:  %history{1:timestamp} = 990455579
                   14229:  %history{2:bar} = foo
                   14230:  %history{2:foo} = notbar
                   14231:  %history{2:keys} = foo:bar:timestamp
                   14232:  %history{2:timestamp} = 990455580
                   14233:  %history{bar} = foo
                   14234:  %history{foo} = notbar
                   14235:  %history{timestamp} = 990455580
                   14236:  %history{version} = 2
                   14237: 
                   14238: Note that the special hash entries C<keys>, C<version> and
                   14239: C<timestamp> were added to the hash. C<version> will be equal to the
                   14240: total number of versions of the data that have been stored. The
                   14241: C<timestamp> attribute will be the UNIX time the hash was
                   14242: stored. C<keys> is available in every historical section to list which
                   14243: keys were added or changed at a specific historical revision of a
                   14244: hash.
                   14245: 
                   14246: B<Warning>: do not store the hash that restore returns directly. This
                   14247: will cause a mess since it will restore the historical keys as if the
                   14248: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14249: 
1.394     bowersj2 14250: Calling convention:
1.191     harris41 14251: 
1.1172.2.27  raeburn  14252:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14253:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14254: 
1.394     bowersj2 14255: For more detailed information, see lonnet specific documentation.
1.191     harris41 14256: 
1.394     bowersj2 14257: =head1 RETURN MESSAGES
1.191     harris41 14258: 
1.394     bowersj2 14259: =over 4
1.191     harris41 14260: 
1.394     bowersj2 14261: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14262: 
1.394     bowersj2 14263: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14264: when the connection is brought back up
1.191     harris41 14265: 
1.394     bowersj2 14266: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14267: for later delivery
1.191     harris41 14268: 
1.967     bisitz   14269: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14270: 
1.394     bowersj2 14271: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14272: that was requested
1.191     harris41 14273: 
1.243     albertel 14274: =back
1.191     harris41 14275: 
1.243     albertel 14276: =head1 PUBLIC SUBROUTINES
1.191     harris41 14277: 
1.243     albertel 14278: =head2 Session Environment Functions
1.191     harris41 14279: 
1.243     albertel 14280: =over 4
1.191     harris41 14281: 
1.394     bowersj2 14282: =item * 
                   14283: X<appenv()>
1.949     raeburn  14284: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14285: the user envirnoment file, and will be restored for each access this
1.620     albertel 14286: user makes during this session, also modifies the %env for the current
1.949     raeburn  14287: process. Optional rolesarrayref - if defined contains a reference to an array
                   14288: of roles which are exempt from the restriction on modifying user.role entries 
                   14289: in the user's environment.db and in %env.    
1.191     harris41 14290: 
                   14291: =item *
1.394     bowersj2 14292: X<delenv()>
1.987     raeburn  14293: B<delenv($delthis,$regexp)>: removes all items from the session
                   14294: environment file that begin with $delthis. If the 
                   14295: optional second arg - $regexp - is true, $delthis is treated as a 
                   14296: regular expression, otherwise \Q$delthis\E is used. 
                   14297: The values are also deleted from the current processes %env.
1.191     harris41 14298: 
1.795     albertel 14299: =item * get_env_multiple($name) 
                   14300: 
                   14301: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14302: values may be defined and end up as an array ref.
                   14303: 
                   14304: returns an array of values
                   14305: 
1.243     albertel 14306: =back
                   14307: 
                   14308: =head2 User Information
1.191     harris41 14309: 
1.243     albertel 14310: =over 4
1.191     harris41 14311: 
                   14312: =item *
1.394     bowersj2 14313: X<queryauthenticate()>
                   14314: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14315: authentication scheme
                   14316: 
                   14317: =item *
1.394     bowersj2 14318: X<authenticate()>
1.1073    raeburn  14319: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14320: authenticate user from domain's lib servers (first use the current
                   14321: one). C<$upass> should be the users password.
1.1073    raeburn  14322: $checkdefauth is optional (value is 1 if a check should be made to
                   14323:    authenticate user using default authentication method, and allow
                   14324:    account creation if username does not have account in the domain).
                   14325: $clientcancheckhost is optional (value is 1 if checking whether the
                   14326:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14327: 
                   14328: =item *
1.394     bowersj2 14329: X<homeserver()>
                   14330: B<homeserver($uname,$udom)>: find the server which has
                   14331: the user's directory and files (there must be only one), this caches
                   14332: the answer, and also caches if there is a borken connection.
1.191     harris41 14333: 
                   14334: =item *
1.394     bowersj2 14335: X<idget()>
                   14336: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14337: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14338: username, and only 1 username per ID in a specific domain) (returns
                   14339: hash: id=>name,id=>name)
1.191     harris41 14340: 
                   14341: =item *
1.394     bowersj2 14342: X<idrget()>
                   14343: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14344: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14345: 
                   14346: =item *
1.394     bowersj2 14347: X<idput()>
                   14348: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14349: 
                   14350: =item *
1.394     bowersj2 14351: X<rolesinit()>
1.1169    droeschl 14352: B<rolesinit($udom,$username)>: get user privileges.
                   14353: returns user role, first access and timer interval hashes
1.243     albertel 14354: 
                   14355: =item *
1.1171    droeschl 14356: X<privileged()>
                   14357: B<privileged($username,$domain)>: returns a true if user has a
                   14358: privileged and active role (i.e. su or dc), false otherwise.
                   14359: 
                   14360: =item *
1.551     albertel 14361: X<getsection()>
                   14362: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14363: course $cname, return section name/number or '' for "not in course"
                   14364: and '-1' for "no section"
                   14365: 
                   14366: =item *
1.394     bowersj2 14367: X<userenvironment()>
                   14368: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14369: passed in @what from the requested user's environment, returns a hash
                   14370: 
1.858     raeburn  14371: =item * 
                   14372: X<userlog_query()>
1.859     albertel 14373: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14374: activity.log file. %filters defines filters applied when parsing the
                   14375: log file. These can be start or end timestamps, or the type of action
                   14376: - log to look for Login or Logout events, check for Checkin or
                   14377: Checkout, role for role selection. The response is in the form
                   14378: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14379: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14380: 
1.243     albertel 14381: =back
                   14382: 
                   14383: =head2 User Roles
                   14384: 
                   14385: =over 4
                   14386: 
                   14387: =item *
                   14388: 
1.1172.2.65  raeburn  14389: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14390: returns codes for allowed actions.
                   14391: 
                   14392: The first argument is required, all others are optional.
                   14393: 
                   14394: $priv is the privilege being checked.
                   14395: $uri contains additional information about what is being checked for access (e.g.,
                   14396: URL, course ID etc.).
                   14397: $symb is the unique resource instance identifier in a course; if needed,
                   14398: but not provided, it will be retrieved via a call to &symbread().
                   14399: $role is the role for which a priv is being checked (only used if priv is evb).
                   14400: $clientip is the user's IP address (only used when checking for access to portfolio
                   14401: files).
                   14402: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14403: prevents recursive calls to &allowed.
                   14404: 
1.243     albertel 14405:  F: full access
                   14406:  U,I,K: authentication modes (cxx only)
                   14407:  '': forbidden
                   14408:  1: user needs to choose course
                   14409:  2: browse allowed
1.766     albertel 14410:  A: passphrase authentication needed
1.1172.2.65  raeburn  14411:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14412: 
                   14413: =item *
                   14414: 
1.1172.2.13  raeburn  14415: constructaccess($url,$setpriv) : check for access to construction space URL
                   14416: 
                   14417: See if the owner domain and name in the URL match those in the
                   14418: expected environment.  If so, return three element list
                   14419: ($ownername,$ownerdomain,$ownerhome).
                   14420: 
                   14421: Otherwise return the null string.
                   14422: 
                   14423: If second argument 'setpriv' is true, it assigns the privileges,
                   14424: and returns the same three element list, unless the owner has
                   14425: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14426: in which case the null string is returned.
                   14427: 
                   14428: =item *
                   14429: 
1.1172.2.84  raeburn  14430: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14431: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14432: for system, domain, and course level. $uname and $udom are optional (current
                   14433: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14434: 
                   14435: =item *
                   14436: 
1.988     raeburn  14437: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14438: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14439: $type is Course (default) or Community.
1.988     raeburn  14440: If $forcedefault evaluates to true, text returned will be default 
                   14441: text for $type. Otherwise, if this is a course, the text returned 
                   14442: will be a custom name for the role (if defined in the course's 
                   14443: environment).  If no custom name is defined the default is returned.
                   14444:    
1.832     raeburn  14445: =item *
                   14446: 
1.1172.2.23  raeburn  14447: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14448: All arguments are optional. Returns a hash of a roles, either for
                   14449: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14450: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14451: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14452: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14453: For each key, value is set to colon-separated start and end times for
                   14454: the role.  If no username and domain are specified, will default to
1.934     raeburn  14455: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14456: of role statuses (active, future or previous), roles 
                   14457: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14458: to restrict the list of roles reported. If no array ref is 
                   14459: provided for types, will default to return only active roles.
1.834     albertel 14460: 
1.1172.2.13  raeburn  14461: =item *
                   14462: 
                   14463: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14464: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14465: 
                   14466: Additional optional arguments are: $type (if role checking is to be restricted
                   14467: to certain user status types -- previous (expired roles), active (currently
                   14468: available roles) or future (roles available in the future), and
                   14469: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14470: have active Domain Coordinator role in course's domain or in additional
                   14471: domains (specified in 'Domains to check for privileged users' in course
                   14472: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14473: 
                   14474: =item *
                   14475: 
                   14476: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14477: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14478: $possdomains and $possroles are optional array refs -- to domains to check and
                   14479: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14480: users' roles.db to check for a dc or su role in any domain. This can be
                   14481: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14482: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14483: this then allows &privileged_by_domain() to be used, which caches the identity
                   14484: of privileged users, eliminating the need for repeated calls to &dump().
                   14485: 
                   14486: =item *
                   14487: 
                   14488: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14489: where the outer hash keys are domains specified in the $possdomains array ref,
                   14490: next inner hash keys are privileged roles specified in the $roles array ref,
                   14491: and the innermost hash contains key = value pairs for username:domain = end:start
                   14492: for active or future "privileged" users with that role in that domain. To avoid
                   14493: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14494: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14495: 
1.243     albertel 14496: =back
                   14497: 
                   14498: =head2 User Modification
                   14499: 
                   14500: =over 4
                   14501: 
                   14502: =item *
                   14503: 
1.957     raeburn  14504: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14505: user for the level given by URL.  Optional start and end dates (leave empty
                   14506: string or zero for "no date")
1.191     harris41 14507: 
                   14508: =item *
                   14509: 
1.243     albertel 14510: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14511: change a users, password, possible return values are: ok,
                   14512: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14513: refused
1.191     harris41 14514: 
                   14515: =item *
                   14516: 
1.243     albertel 14517: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14518: 
                   14519: =item *
                   14520: 
1.1058    raeburn  14521: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14522:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14523: 
                   14524: will update user information (firstname,middlename,lastname,generation,
                   14525: permanentemail), and if forceid is true, student/employee ID also.
                   14526: A user's institutional affiliation(s) can also be updated.
                   14527: User information fields will not be overwritten with empty entries 
                   14528: unless the field is included in the $candelete array reference.
                   14529: This array is included when a single user is modified via "Manage Users",
                   14530: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14531: 
                   14532: =item *
                   14533: 
1.286     matthew  14534: modifystudent
                   14535: 
1.957     raeburn  14536: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14537: The course id is resolved based on the current user's environment.  
                   14538: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14539: associated with a course.
                   14540: 
1.297     matthew  14541: This call is essentially a wrapper for lonnet::modifyuser and
                   14542: lonnet::modify_student_enrollment
1.286     matthew  14543: 
                   14544: Inputs: 
                   14545: 
                   14546: =over 4
                   14547: 
1.957     raeburn  14548: =item B<$udom> Student's loncapa domain
1.286     matthew  14549: 
1.957     raeburn  14550: =item B<$uname> Student's loncapa login name
1.286     matthew  14551: 
1.964     bisitz   14552: =item B<$uid> Student/Employee ID
1.286     matthew  14553: 
1.957     raeburn  14554: =item B<$umode> Student's authentication mode
1.286     matthew  14555: 
1.957     raeburn  14556: =item B<$upass> Student's password
1.286     matthew  14557: 
1.957     raeburn  14558: =item B<$first> Student's first name
1.286     matthew  14559: 
1.957     raeburn  14560: =item B<$middle> Student's middle name
1.286     matthew  14561: 
1.957     raeburn  14562: =item B<$last> Student's last name
1.286     matthew  14563: 
1.957     raeburn  14564: =item B<$gene> Student's generation
1.286     matthew  14565: 
1.957     raeburn  14566: =item B<$usec> Student's section in course
1.286     matthew  14567: 
                   14568: =item B<$end> Unix time of the roles expiration
                   14569: 
                   14570: =item B<$start> Unix time of the roles start date
                   14571: 
                   14572: =item B<$forceid> If defined, allow $uid to be changed
                   14573: 
                   14574: =item B<$desiredhome> server to use as home server for student
                   14575: 
1.957     raeburn  14576: =item B<$email> Student's permanent e-mail address
                   14577: 
                   14578: =item B<$type> Type of enrollment (auto or manual)
                   14579: 
1.963     raeburn  14580: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14581: 
                   14582: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14583: 
1.963     raeburn  14584: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14585: 
1.963     raeburn  14586: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14587: 
1.1172.2.19  raeburn  14588: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14589: 
                   14590: =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  14591: 
1.286     matthew  14592: =back
1.297     matthew  14593: 
                   14594: =item *
                   14595: 
                   14596: modify_student_enrollment
                   14597: 
1.1172.2.31  raeburn  14598: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14599: 'role.request.course' must be defined for this function to proceed.
                   14600: 
                   14601: Inputs:
                   14602: 
                   14603: =over 4
                   14604: 
1.1172.2.31  raeburn  14605: =item $udom, student's domain
1.297     matthew  14606: 
1.1172.2.31  raeburn  14607: =item $uname, student's name
1.297     matthew  14608: 
1.1172.2.31  raeburn  14609: =item $uid, student's user id
1.297     matthew  14610: 
1.1172.2.31  raeburn  14611: =item $first, student's first name
1.297     matthew  14612: 
                   14613: =item $middle
                   14614: 
                   14615: =item $last
                   14616: 
                   14617: =item $gene
                   14618: 
                   14619: =item $usec
                   14620: 
                   14621: =item $end
                   14622: 
                   14623: =item $start
                   14624: 
1.957     raeburn  14625: =item $type
                   14626: 
                   14627: =item $locktype
                   14628: 
                   14629: =item $cid
                   14630: 
                   14631: =item $selfenroll
                   14632: 
                   14633: =item $context
                   14634: 
1.1172.2.19  raeburn  14635: =item $credits, number of credits student will earn from this class
                   14636: 
1.1172.2.76  raeburn  14637: =item $instsec, institutional course section code for student
                   14638: 
1.297     matthew  14639: =back
                   14640: 
1.191     harris41 14641: 
                   14642: =item *
                   14643: 
1.243     albertel 14644: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14645: custom role; give a custom role to a user for the level given by URL.  Specify
                   14646: name and domain of role author, and role name
1.191     harris41 14647: 
                   14648: =item *
                   14649: 
1.243     albertel 14650: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14651: 
                   14652: =item *
                   14653: 
1.243     albertel 14654: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14655: 
                   14656: =back
                   14657: 
                   14658: =head2 Course Infomation
                   14659: 
                   14660: =over 4
1.191     harris41 14661: 
                   14662: =item *
                   14663: 
1.1118    foxr     14664: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14665: specified course id, including all environment settings for the
                   14666: course, the description of the course will be in the hash under the
                   14667: key 'description'
1.191     harris41 14668: 
1.1118    foxr     14669: $options is an optional parameter that if supplied is a hash reference that controls
                   14670: what how this function works.  It has the following key/values:
                   14671: 
                   14672: =over 4
                   14673: 
                   14674: =item freshen_cache
                   14675: 
                   14676: If defined, and the environment cache for the course is valid, it is 
                   14677: returned in the returned hash.
                   14678: 
                   14679: =item one_time
                   14680: 
                   14681: If defined, the last cache time is set to _now_
                   14682: 
                   14683: =item user
                   14684: 
                   14685: If defined, the supplied username is used instead of the current user.
                   14686: 
                   14687: 
                   14688: =back
                   14689: 
1.191     harris41 14690: =item *
                   14691: 
1.624     albertel 14692: resdata($name,$domain,$type,@which) : request for current parameter
                   14693: setting for a specific $type, where $type is either 'course' or 'user',
                   14694: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14695: answers for 10 minutes.
1.243     albertel 14696: 
1.877     foxr     14697: =item *
                   14698: 
                   14699: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14700: data base, returning a hash that is keyed by the resource name and has
                   14701: values that are the resource value.  I believe that the timestamps and
                   14702: versions are also returned.
                   14703: 
1.1172.2.31  raeburn  14704: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14705: supplemental content area. This routine caches the number of files for
                   14706: 10 minutes.
                   14707: 
1.243     albertel 14708: =back
                   14709: 
                   14710: =head2 Course Modification
                   14711: 
                   14712: =over 4
1.191     harris41 14713: 
                   14714: =item *
                   14715: 
1.243     albertel 14716: writecoursepref($courseid,%prefs) : write preferences (environment
                   14717: database) for a course
1.191     harris41 14718: 
                   14719: =item *
                   14720: 
1.1011    raeburn  14721: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14722: 
                   14723: =item *
                   14724: 
1.1038    raeburn  14725: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14726: 
1.1167    droeschl 14727: =item *
                   14728: 
                   14729: is_course($courseid), is_course($cdom, $cnum)
                   14730: 
                   14731: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14732: two component version $cdom, $cnum. It checks if the specified course exists.
                   14733: 
                   14734: Returns:
                   14735:     undef if the course doesn't exist, otherwise
                   14736:     in scalar context the combined courseid.
                   14737:     in list context the two components of the course identifier, domain and 
                   14738:     courseid.    
                   14739: 
1.243     albertel 14740: =back
                   14741: 
1.1172.2.109  raeburn  14742: =head2 Bubblesheet Configuration
                   14743: 
                   14744: =over 4
                   14745: 
                   14746: =item *
                   14747: 
                   14748: get_scantron_config($which)
                   14749: 
                   14750: $which - the name of the configuration to parse from the file.
                   14751: 
                   14752: Parses and returns the bubblesheet configuration line selected as a
                   14753: hash of configuration file fields.
                   14754: 
                   14755: 
                   14756: Returns:
                   14757:     If the named configuration is not in the file, an empty
                   14758:     hash is returned.
                   14759: 
                   14760:     a hash with the fields
                   14761:       name         - internal name for the this configuration setup
                   14762:       description  - text to display to operator that describes this config
                   14763:       CODElocation - if 0 or the string 'none'
                   14764:                           - no CODE exists for this config
                   14765:                      if -1 || the string 'letter'
                   14766:                           - a CODE exists for this config and is
                   14767:                             a string of letters
                   14768:                      Unsupported value (but planned for future support)
                   14769:                           if a positive integer
                   14770:                                - The CODE exists as the first n items from
                   14771:                                  the question section of the form
                   14772:                           if the string 'number'
                   14773:                                - The CODE exists for this config and is
                   14774:                                  a string of numbers
                   14775:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14776:                      the CODE starts
                   14777:       CODElength  - length of the CODE
                   14778:       IDstart     - column where the student/employee ID starts
                   14779:       IDlength    - length of the student/employee ID info
                   14780:       Qstart      - column where the information from the bubbled
                   14781:                     'questions' start
                   14782:       Qlength     - number of columns comprising a single bubble line from
                   14783:                     the sheet. (usually either 1 or 10)
                   14784:       Qon         - either a single character representing the character used
                   14785:                     to signal a bubble was chosen in the positional setup, or
                   14786:                     the string 'letter' if the letter of the chosen bubble is
                   14787:                     in the final, or 'number' if a number representing the
                   14788:                     chosen bubble is in the file (1->A 0->J)
                   14789:       Qoff        - the character used to represent that a bubble was
                   14790:                     left blank
                   14791:       PaperID     - if the scanning process generates a unique number for each
                   14792:                     sheet scanned the column that this ID number starts in
                   14793:       PaperIDlength - number of columns that comprise the unique ID number
                   14794:                       for the sheet of paper
                   14795:       FirstName   - column that the first name starts in
                   14796:       FirstNameLength - number of columns that the first name spans
                   14797:       LastName    - column that the last name starts in
                   14798:       LastNameLength - number of columns that the last name spans
                   14799:       BubblesPerRow - number of bubbles available in each row used to
                   14800:                       bubble an answer. (If not specified, 10 assumed).
                   14801: 
                   14802: 
                   14803: =item *
                   14804: 
                   14805: get_scantronformat_file($cdom)
                   14806: 
                   14807: $cdom - the course's domain (optional); if not supplied, uses
                   14808: domain for current $env{'request.course.id'}.
                   14809: 
                   14810: Returns an array containing lines from the scantron format file for
                   14811: the domain of the course.
                   14812: 
                   14813: If a url for a custom.tab file is listed in domain's configuration.db,
                   14814: lines are from this file.
                   14815: 
                   14816: Otherwise, if a default.tab has been published in RES space by the
                   14817: domainconfig user, lines are from this file.
                   14818: 
                   14819: Otherwise, fall back to getting lines from the legacy file on the
                   14820: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14821: 
                   14822: =back
                   14823: 
1.243     albertel 14824: =head2 Resource Subroutines
                   14825: 
                   14826: =over 4
1.191     harris41 14827: 
                   14828: =item *
                   14829: 
1.243     albertel 14830: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14831: 
                   14832: =item *
                   14833: 
1.243     albertel 14834: repcopy($filename) : subscribes to the requested file, and attempts to
                   14835: replicate from the owning library server, Might return
1.607     raeburn  14836: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14837: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14838: resource. Expects the local filesystem pathname
                   14839: (/home/httpd/html/res/....)
                   14840: 
                   14841: =back
                   14842: 
                   14843: =head2 Resource Information
                   14844: 
                   14845: =over 4
1.191     harris41 14846: 
                   14847: =item *
                   14848: 
1.1172.2.28  raeburn  14849: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14850: and returns the value of a variety of different possible values,
                   14851: $varname should be a request string, and the other parameters can be
                   14852: used to specify who and what one is asking about. Ordinarily, $cid 
                   14853: does not need to be specified, as it is retrived from 
                   14854: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14855: within lonuserstate::loadmap() when initializing a course, before
                   14856: $env{'request.course.id'} has been set, so it needs to be provided
                   14857: in that one case.
1.243     albertel 14858: 
                   14859: Possible values for $varname are environment.lastname (or other item
                   14860: from the envirnment hash), user.name (or someother aspect about the
                   14861: user), resource.0.maxtries (or some other part and parameter of a
                   14862: resource)
1.204     albertel 14863: 
                   14864: =item *
                   14865: 
1.243     albertel 14866: directcondval($number) : get current value of a condition; reads from a state
                   14867: string
1.204     albertel 14868: 
                   14869: =item *
                   14870: 
1.243     albertel 14871: condval($condidx) : value of condition index based on state
1.204     albertel 14872: 
                   14873: =item *
                   14874: 
1.243     albertel 14875: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14876: resource's metadata, $what should be either a specific key, or either
                   14877: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14878: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14879: 
                   14880: this function automatically caches all requests
1.191     harris41 14881: 
                   14882: =item *
                   14883: 
1.243     albertel 14884: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14885: network of library servers; returns file handle of where SQL and regex results
                   14886: will be stored for query
1.191     harris41 14887: 
                   14888: =item *
                   14889: 
1.1172.2.66  raeburn  14890: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14891: return symbolic list entry (all arguments optional).
                   14892: 
                   14893: Args: filename is the filename (including path) for the file for which a symb
                   14894: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14895: to check access status if more than one resource was found in the bighash
                   14896: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14897: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14898: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14899: cause possible symbs to be checked to determine if they are subject to content
                   14900: blocking, if so they will not be included as possible symbs; possibles is a
                   14901: ref to a hash, which, as a side effect, will be populated with all possible
                   14902: symbs (content blocking not tested).
                   14903: 
1.243     albertel 14904: returns the data handle
1.191     harris41 14905: 
                   14906: =item *
                   14907: 
1.1172.2.17  raeburn  14908: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14909: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14910: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14911: on failure, user must be in a course, as it assumes the existence of
                   14912: the course initial hash, and uses $env('request.course.id'}.  The third
                   14913: arg is an optional reference to a scalar.  If this arg is passed in the
                   14914: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14915: encrypted; otherwise it will be null.
1.243     albertel 14916: 
1.191     harris41 14917: =item *
                   14918: 
1.243     albertel 14919: symbclean($symb) : removes versions numbers from a symb, returns the
                   14920: cleaned symb
1.191     harris41 14921: 
                   14922: =item *
                   14923: 
1.243     albertel 14924: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14925: course map, user must be in a course for it to work.
1.191     harris41 14926: 
                   14927: =item *
                   14928: 
1.243     albertel 14929: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14930: 
                   14931: =item *
                   14932: 
1.243     albertel 14933: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14934: a random seed, all arguments are optional, if they aren't sent it uses the
                   14935: environment to derive them. Note: if symb isn't sent and it can't get one
                   14936: from &symbread it will use the current time as its return value
1.191     harris41 14937: 
                   14938: =item *
                   14939: 
1.243     albertel 14940: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14941: unfakeable, receipt
1.191     harris41 14942: 
                   14943: =item *
                   14944: 
1.620     albertel 14945: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14946: 
                   14947: =item *
                   14948: 
1.243     albertel 14949: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14950: 
                   14951: =item *
                   14952: 
1.243     albertel 14953: 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 14954: 
                   14955: =item *
                   14956: 
1.243     albertel 14957: 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 14958: 
                   14959: =item *
                   14960: 
1.243     albertel 14961: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14962: 
                   14963: =item *
                   14964: 
1.243     albertel 14965: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14966: forcing spreadsheet to reevaluate the resource scores next time.
                   14967: 
1.1172.2.13  raeburn  14968: =item *
                   14969: 
                   14970: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14971: when viewing in course context.
                   14972: 
                   14973:  input: six args -- filename (decluttered), course number, course domain,
                   14974:                     url, symb (if registered) and group (if this is a
                   14975:                     group item -- e.g., bulletin board, group page etc.).
                   14976: 
                   14977:  output: array of five scalars --
                   14978:          $cfile -- url for file editing if editable on current server
                   14979:          $home -- homeserver of resource (i.e., for author if published,
                   14980:                                           or course if uploaded.).
                   14981:          $switchserver --  1 if server switch will be needed.
                   14982:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14983:          $forceview -- 1 if icon/link should be to go to view mode
                   14984: 
                   14985: =item *
                   14986: 
                   14987: is_course_upload($file,$cnum,$cdom)
                   14988: 
                   14989: Used in course context to determine if current file was uploaded to
                   14990: the course (i.e., would be found in /userfiles/docs on the course's
                   14991: homeserver.
                   14992: 
                   14993:   input: 3 args -- filename (decluttered), course number and course domain.
                   14994:   output: boolean -- 1 if file was uploaded.
                   14995: 
1.243     albertel 14996: =back
                   14997: 
                   14998: =head2 Storing/Retreiving Data
                   14999: 
                   15000: =over 4
1.191     harris41 15001: 
                   15002: =item *
                   15003: 
1.1172.2.64  raeburn  15004: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15005: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15006: the remaining args aren't required and if they aren't passed or are '' they will
                   15007: be derived from the env (with the exception of $laststore, which is an
                   15008: optional arg used when a user's submission is stored in grading).
                   15009: $laststore is $version=$timestamp, where $version is the most recent version
                   15010: number retrieved for the corresponding $symb in the $namespace db file, and
                   15011: $timestamp is the timestamp for that transaction (UNIX time).
                   15012: $laststore is currently only passed when cstore() is called by
                   15013: structuretags::finalize_storage().
1.191     harris41 15014: 
                   15015: =item *
                   15016: 
1.1172.2.64  raeburn  15017: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15018: but uses critical subroutine
1.191     harris41 15019: 
                   15020: =item *
                   15021: 
1.243     albertel 15022: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15023: all args are optional
1.191     harris41 15024: 
                   15025: =item *
                   15026: 
1.717     albertel 15027: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15028: dumps the complete (or key matching regexp) namespace into a hash
                   15029: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15030: normally &store()ed into
                   15031: 
                   15032: $range should be either an integer '100' (give me the first 100
                   15033:                                            matching records)
                   15034:               or be  two integers sperated by a - with no spaces
                   15035:                  '30-50' (give me the 30th through the 50th matching
                   15036:                           records)
                   15037: 
                   15038: 
                   15039: =item *
                   15040: 
1.1172.2.59  raeburn  15041: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15042: replaces a &store() version of data with a replacement set of data
                   15043: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15044: reference. If $tolog is true, the transaction is logged in the courselog
                   15045: with an action=PUTSTORE.
1.717     albertel 15046: 
                   15047: =item *
                   15048: 
1.243     albertel 15049: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15050: works very similar to store/cstore, but all data is stored in a
                   15051: temporary location and can be reset using tmpreset, $storehash should
                   15052: be a hash reference, returns nothing on success
1.191     harris41 15053: 
                   15054: =item *
                   15055: 
1.243     albertel 15056: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15057: similar to restore, but all data is stored in a temporary location and
                   15058: can be reset using tmpreset. Returns a hash of values on success,
                   15059: error string otherwise.
1.191     harris41 15060: 
                   15061: =item *
                   15062: 
1.243     albertel 15063: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15064: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15065: 
                   15066: =item *
                   15067: 
1.243     albertel 15068: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15069: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15070: 
                   15071: =item *
                   15072: 
1.243     albertel 15073: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15074: namesp ($udom and $uname are optional)
1.191     harris41 15075: 
                   15076: =item *
                   15077: 
1.702     albertel 15078: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15079: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15080: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15081: 
1.702     albertel 15082: $range should be either an integer '100' (give me the first 100
                   15083:                                            matching records)
                   15084:               or be  two integers sperated by a - with no spaces
                   15085:                  '30-50' (give me the 30th through the 50th matching
                   15086:                           records)
1.449     matthew  15087: =item *
                   15088: 
                   15089: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15090: $store can be a scalar, an array reference, or if the amount to be 
                   15091: incremented is > 1, a hash reference.
                   15092: 
                   15093: ($udom and $uname are optional)
1.191     harris41 15094: 
                   15095: =item *
                   15096: 
1.243     albertel 15097: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15098: ($udom and $uname are optional)
1.191     harris41 15099: 
                   15100: =item *
                   15101: 
1.243     albertel 15102: cput($namespace,$storehash,$udom,$uname) : critical put
                   15103: ($udom and $uname are optional)
1.191     harris41 15104: 
                   15105: =item *
                   15106: 
1.748     albertel 15107: newput($namespace,$storehash,$udom,$uname) :
                   15108: 
                   15109: Attempts to store the items in the $storehash, but only if they don't
                   15110: currently exist, if this succeeds you can be certain that you have 
                   15111: successfully created a new key value pair in the $namespace db.
                   15112: 
                   15113: 
                   15114: Args:
                   15115:  $namespace: name of database to store values to
                   15116:  $storehash: hashref to store to the db
                   15117:  $udom: (optional) domain of user containing the db
                   15118:  $uname: (optional) name of user caontaining the db
                   15119: 
                   15120: Returns:
                   15121:  'ok' -> succeeded in storing all keys of $storehash
                   15122:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15123:                         least <key> already existed in the db (other
                   15124:                         requested keys may also already exist)
1.967     bisitz   15125:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15126:  'con_lost' -> unable to contact request server
                   15127:  'refused' -> action was not allowed by remote machine
                   15128: 
                   15129: 
                   15130: =item *
                   15131: 
1.243     albertel 15132: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15133: reference filled in from namesp (encrypts the return communication)
                   15134: ($udom and $uname are optional)
1.191     harris41 15135: 
                   15136: =item *
                   15137: 
1.243     albertel 15138: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15139: critical subroutine
                   15140: 
1.806     raeburn  15141: =item *
                   15142: 
1.860     raeburn  15143: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15144: array reference filled in from namespace found in domain level on either
                   15145: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15146: 
                   15147: =item *
                   15148: 
1.860     raeburn  15149: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15150: domain level either on specified domain server ($uhome) or primary domain 
                   15151: server ($udom and $uhome are optional)
1.806     raeburn  15152: 
1.943     raeburn  15153: =item * 
                   15154: 
1.1172.2.35  raeburn  15155: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15156: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15157: the target domain.
                   15158: 
                   15159: May also include additional key => value pairs for the following groups:
                   15160: 
                   15161: =over
                   15162: 
                   15163: =item
                   15164: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15165: 
                   15166: =over
                   15167: 
                   15168: =item defaultquota, authorquota
                   15169: 
                   15170: =back
                   15171: 
                   15172: =item
                   15173: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15174: portfolio for users).
                   15175: 
                   15176: =over
                   15177: 
                   15178: =item
                   15179: aboutme, blog, webdav, portfolio
                   15180: 
                   15181: =back
                   15182: 
                   15183: =item
                   15184: requestcourses: ability to request courses, and how requests are processed.
                   15185: 
                   15186: =over
                   15187: 
                   15188: =item
1.1172.2.37  raeburn  15189: official, unofficial, community, textbook
1.1172.2.35  raeburn  15190: 
                   15191: =back
                   15192: 
                   15193: =item
                   15194: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15195: 
                   15196: =over
                   15197: 
                   15198: =item
1.1172.2.44  raeburn  15199: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15200: 
                   15201: =back
                   15202: 
                   15203: =item
                   15204: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15205: for course's uploaded content.
                   15206: 
                   15207: =over
                   15208: 
                   15209: =item
1.1172.2.68  raeburn  15210: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15211: communityquota, textbookquota
1.1172.2.35  raeburn  15212: 
                   15213: =back
                   15214: 
                   15215: =item
                   15216: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15217: on your servers.
                   15218: 
                   15219: =over
                   15220: 
                   15221: =item
                   15222: remotesessions, hostedsessions
                   15223: 
                   15224: =back
                   15225: 
                   15226: =back
                   15227: 
                   15228: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15229: utility to create a configuration.db file on a domain's primary library server
                   15230: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15231: -- corresponding values are authentication type (internal, krb4, krb5,
                   15232: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15233: will be available. Values are retrieved from cache (if current), unless the
                   15234: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15235: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15236: 
                   15237: Typical usage:
1.943     raeburn  15238: 
1.1172.2.35  raeburn  15239: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15240: 
1.243     albertel 15241: =back
                   15242: 
                   15243: =head2 Network Status Functions
                   15244: 
                   15245: =over 4
1.191     harris41 15246: 
                   15247: =item *
                   15248: 
1.1137    raeburn  15249: dirlist() : return directory list based on URI (first arg).
                   15250: 
                   15251: Inputs: 1 required, 5 optional.
                   15252: 
                   15253: =over
                   15254: 
                   15255: =item 
                   15256: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15257: 
                   15258: =item
                   15259: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15260: 
                   15261: =item
                   15262: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15263: 
                   15264: =item
                   15265: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15266: 
                   15267: =item
                   15268: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15269: 
                   15270: =item 
                   15271: $alternateRoot - path to prepend in place of path from $uri.
                   15272: 
                   15273: =back
                   15274: 
                   15275: Returns: Array of up to two items.
                   15276: 
                   15277: =over
                   15278: 
                   15279: a reference to an array of files/subdirectories
                   15280: 
                   15281: =over
                   15282: 
                   15283: Each element in the array of files/subdirectories is a & separated list of
                   15284: item name and the result of running stat on the item.  If dirlist was requested
                   15285: for a file instead of a directory, the item name will be ''. For a directory 
                   15286: listing, if the item is a metadata file, the element will end &N&M 
                   15287: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15288: default copyright set (1).  
                   15289: 
                   15290: =back
                   15291: 
                   15292: a scalar containing error condition (if encountered).
                   15293: 
                   15294: =over
                   15295: 
                   15296: =item 
                   15297: no_host (no homeserver identified for $username:$domain).
                   15298: 
                   15299: =item 
                   15300: no_such_host (server contacted for listing not identified as valid host).
                   15301: 
                   15302: =item 
                   15303: con_lost (connection to remote server failed).
                   15304: 
                   15305: =item 
                   15306: refused (invalid $username:$domain received on lond side).
                   15307: 
                   15308: =item 
                   15309: no_such_dir (directory at specified path on lond side does not exist). 
                   15310: 
                   15311: =item 
                   15312: empty (directory at specified path on lond side is empty).
                   15313: 
                   15314: =over
                   15315: 
                   15316: This is currently not encountered because the &ls3, &ls2, 
                   15317: &ls (_handler) routines on the lond side do not filter out
                   15318: . and .. from a directory listing. 
                   15319: 
                   15320: =back
                   15321: 
                   15322: =back
                   15323: 
                   15324: =back
1.191     harris41 15325: 
                   15326: =item *
                   15327: 
1.243     albertel 15328: spareserver() : find server with least workload from spare.tab
                   15329: 
1.986     foxr     15330: 
                   15331: =item *
                   15332: 
                   15333: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15334: if there is no corresponding loncapa host.
                   15335: 
1.243     albertel 15336: =back
                   15337: 
1.986     foxr     15338: 
1.243     albertel 15339: =head2 Apache Request
                   15340: 
                   15341: =over 4
1.191     harris41 15342: 
                   15343: =item *
                   15344: 
1.243     albertel 15345: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15346: localhost, posts hash
                   15347: 
                   15348: =back
                   15349: 
                   15350: =head2 Data to String to Data
                   15351: 
                   15352: =over 4
1.191     harris41 15353: 
                   15354: =item *
                   15355: 
1.243     albertel 15356: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15357: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15358: 
                   15359: =item *
                   15360: 
1.243     albertel 15361: hashref2str($hashref) : convert a hashref into a string complete with
                   15362: escaping and '=' and '&' separators, supports elements that are
                   15363: arrayrefs and hashrefs
1.191     harris41 15364: 
                   15365: =item *
                   15366: 
1.243     albertel 15367: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15368: with escaping and '&' separators, supports elements that are arrayrefs
                   15369: and hashrefs
1.191     harris41 15370: 
                   15371: =item *
                   15372: 
1.243     albertel 15373: str2hash($string) : convert string to hash using unescaping and
                   15374: splitting on '=' and '&', supports elements that are arrayrefs and
                   15375: hashrefs
1.191     harris41 15376: 
                   15377: =item *
                   15378: 
1.243     albertel 15379: str2array($string) : convert string to hash using unescaping and
                   15380: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15381: 
                   15382: =back
                   15383: 
                   15384: =head2 Logging Routines
                   15385: 
                   15386: 
                   15387: These routines allow one to make log messages in the lonnet.log and
                   15388: lonnet.perm logfiles.
1.191     harris41 15389: 
1.1119    foxr     15390: =over 4
                   15391: 
1.191     harris41 15392: =item *
                   15393: 
1.243     albertel 15394: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15395: 
                   15396: =item *
                   15397: 
1.243     albertel 15398: logthis() : append message to the normal lonnet.log file, it gets
                   15399: preiodically rolled over and deleted.
1.191     harris41 15400: 
                   15401: =item *
                   15402: 
1.243     albertel 15403: logperm() : append a permanent message to lonnet.perm.log, this log
                   15404: file never gets deleted by any automated portion of the system, only
                   15405: messages of critical importance should go in here.
                   15406: 
1.1119    foxr     15407: 
1.243     albertel 15408: =back
                   15409: 
                   15410: =head2 General File Helper Routines
                   15411: 
                   15412: =over 4
1.191     harris41 15413: 
                   15414: =item *
                   15415: 
1.481     raeburn  15416: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15417: (a) files in /uploaded
                   15418:   (i) If a local copy of the file exists - 
                   15419:       compares modification date of local copy with last-modified date for 
                   15420:       definitive version stored on home server for course. If local copy is 
                   15421:       stale, requests a new version from the home server and stores it. 
                   15422:       If the original has been removed from the home server, then local copy 
                   15423:       is unlinked.
                   15424:   (ii) If local copy does not exist -
                   15425:       requests the file from the home server and stores it. 
                   15426:   
                   15427:   If $caller is 'uploadrep':  
                   15428:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15429:     for request for files originally uploaded via DOCS. 
                   15430:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15431:   
                   15432:   Otherwise:
                   15433:      This indicates a call from the content generation phase of the request.
                   15434:      -  returns the entire contents of the file or -1.
                   15435:      
                   15436: (b) files in /res
                   15437:    - returns the entire contents of a file or -1; 
                   15438:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15439: 
1.712     albertel 15440: 
                   15441: =item *
                   15442: 
                   15443: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15444:                   reference
                   15445: 
                   15446: returns either a stat() list of data about the file or an empty list
                   15447: if the file doesn't exist or couldn't find out about it (connection
                   15448: problems or user unknown)
                   15449: 
1.191     harris41 15450: =item *
                   15451: 
1.243     albertel 15452: filelocation($dir,$file) : returns file system location of a file
                   15453: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15454: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15455: and a file of ../bob will become /a/bob)
1.191     harris41 15456: 
                   15457: =item *
                   15458: 
                   15459: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15460: filelocation except for hrefs
                   15461: 
                   15462: =item *
                   15463: 
1.1172.2.49  raeburn  15464: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15465: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15466: 
1.243     albertel 15467: =back
                   15468: 
1.608     albertel 15469: =head2 Usererfile file routines (/uploaded*)
                   15470: 
                   15471: =over 4
                   15472: 
                   15473: =item *
                   15474: 
                   15475: userfileupload(): main rotine for putting a file in a user or course's
                   15476:                   filespace, arguments are,
                   15477: 
1.620     albertel 15478:  formname - required - this is the name of the element in $env where the
1.608     albertel 15479:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15480:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15481:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15482:  context - if coursedoc, store the file in the course of the active role
                   15483:              of the current user; 
                   15484:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15485:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15486:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15487:          if undefined, it will be placed in "unknown"
                   15488: 
                   15489:  (This routine calls clean_filename() to remove any dangerous
                   15490:  characters from the filename, and then calls finuserfileupload() to
                   15491:  complete the transaction)
                   15492: 
                   15493:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15494:  and /adm/notfound.html if unsuccessful
                   15495: 
                   15496: =item *
                   15497: 
                   15498: clean_filename(): routine for cleaing a filename up for storage in
                   15499:                  userfile space, argument is:
                   15500: 
                   15501:  filename - proposed filename
                   15502: 
                   15503: returns: the new clean filename
                   15504: 
                   15505: =item *
                   15506: 
1.1090    raeburn  15507: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15508: userspace, probably shouldn't be called directly
                   15509: 
                   15510:   docuname: username or courseid of destination for the file
                   15511:   docudom: domain of user/course of destination for the file
                   15512:   formname: same as for userfileupload()
1.1090    raeburn  15513:   fname: filename (including subdirectories) for the file
                   15514:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15515:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15516:   allfiles: reference to hash used to store objects found by parser
                   15517:   codebase: reference to hash used for codebases of java objects found by parser
                   15518:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15519:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15520:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15521:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15522:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15523:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15524:   mimetype: reference to scalar to accommodate mime type determined
                   15525:             from File::MMagic if $parser = parse.
1.608     albertel 15526: 
                   15527:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15528:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15529:  was 'overwrite').
                   15530:  
1.608     albertel 15531: 
                   15532: =item *
                   15533: 
                   15534: renameuserfile(): renames an existing userfile to a new name
                   15535: 
                   15536:   Args:
                   15537:    docuname: username or courseid of destination for the file
                   15538:    docudom: domain of user/course of destination for the file
                   15539:    old: current file name (including any subdirs under userfiles)
                   15540:    new: desired file name (including any subdirs under userfiles)
                   15541: 
                   15542: =item *
                   15543: 
                   15544: mkdiruserfile(): creates a directory is a userfiles dir
                   15545: 
                   15546:   Args:
                   15547:    docuname: username or courseid of destination for the file
                   15548:    docudom: domain of user/course of destination for the file
                   15549:    dir: dir to create (including any subdirs under userfiles)
                   15550: 
                   15551: =item *
                   15552: 
                   15553: removeuserfile(): removes a file that exists in userfiles
                   15554: 
                   15555:   Args:
                   15556:    docuname: username or courseid of destination for the file
                   15557:    docudom: domain of user/course of destination for the file
                   15558:    fname: filname to delete (including any subdirs under userfiles)
                   15559: 
                   15560: =item *
                   15561: 
                   15562: removeuploadedurl(): convience function for removeuserfile()
                   15563: 
                   15564:   Args:
                   15565:    url:  a full /uploaded/... url to delete
                   15566: 
1.747     albertel 15567: =item * 
                   15568: 
                   15569: get_portfile_permissions():
                   15570:   Args:
                   15571:     domain: domain of user or course contain the portfolio files
                   15572:     user: name of user or num of course contain the portfolio files
                   15573:   Returns:
                   15574:     hashref of a dump of the proper file_permissions.db
                   15575:    
                   15576: 
                   15577: =item * 
                   15578: 
                   15579: get_access_controls():
                   15580: 
                   15581: Args:
                   15582:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15583:   group: (optional) the group you want the files associated with
                   15584:   file: (optional) the file you want access info on
                   15585: 
                   15586: Returns:
1.749     raeburn  15587:     a hash (keys are file names) of hashes containing
                   15588:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15589:         values are XML containing access control settings (see below) 
1.747     albertel 15590: 
                   15591: Internal notes:
                   15592: 
1.749     raeburn  15593:  access controls are stored in file_permissions.db as key=value pairs.
                   15594:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15595:         where scope -> public,guest,course,group,domains or users.
                   15596:               end -> UNIX time for end of access (0 -> no end date)
                   15597:               start -> UNIX time for start of access
                   15598: 
                   15599:     value -> XML description of access control
                   15600:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15601:             <start></start>
                   15602:             <end></end>
                   15603: 
                   15604:             <password></password>  for scope type = guest
                   15605: 
                   15606:             <domain></domain>     for scope type = course or group
                   15607:             <number></number>
                   15608:             <roles id="">
                   15609:              <role></role>
                   15610:              <access></access>
                   15611:              <section></section>
                   15612:              <group></group>
                   15613:             </roles>
                   15614: 
                   15615:             <dom></dom>         for scope type = domains
                   15616: 
                   15617:             <users>             for scope type = users
                   15618:              <user>
                   15619:               <uname></uname>
                   15620:               <udom></udom>
                   15621:              </user>
                   15622:             </users>
                   15623:            </scope> 
                   15624:               
                   15625:  Access data is also aggregated for each file in an additional key=value pair:
                   15626:  key -> path to file/file_name\0accesscontrol 
                   15627:  value -> reference to hash
                   15628:           hash contains key = value pairs
                   15629:           where key = uniqueID:scope_end_start
                   15630:                 value = UNIX time record was last updated
                   15631: 
                   15632:           Used to improve speed of look-ups of access controls for each file.  
                   15633:  
                   15634:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15635: 
1.1172.2.13  raeburn  15636: =item *
                   15637: 
1.749     raeburn  15638: modify_access_controls():
                   15639: 
                   15640: Modifies access controls for a portfolio file
                   15641: Args
                   15642: 1. file name
                   15643: 2. reference to hash of required changes,
                   15644: 3. domain
                   15645: 4. username
                   15646:   where domain,username are the domain of the portfolio owner 
                   15647:   (either a user or a course) 
                   15648: 
                   15649: Returns:
                   15650: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15651: 2. result of deletions ('ok' or 'error', with error message).
                   15652: 3. reference to hash of any new or updated access controls.
                   15653: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15654:    key = integer (inbound ID)
1.1172.2.13  raeburn  15655:    value = uniqueID
                   15656: 
                   15657: =item *
                   15658: 
                   15659: get_timebased_id():
                   15660: 
                   15661: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15662: course via the Course Editor (e.g., folders, composite pages,
                   15663: group bulletin boards).
                   15664: 
                   15665: Args: (first three required; six others optional)
                   15666: 
                   15667: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15668:    docssequence, or name of group
                   15669: 
                   15670: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15671:    e.g., num, boardids
                   15672: 
                   15673: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15674:    file will be named nohist_namespace.db
                   15675: 
                   15676: 4. cdom: domain of course; default is current course domain from %env
                   15677: 
                   15678: 5. cnum: course number; default is current course number from %env
                   15679: 
                   15680: 6. idtype: set to concat if an additional digit is to be appended to the
                   15681:    unix timestamp to form the suffix, if the plain timestamp is already
                   15682:    in use.  Default is to not do this, but simply increment the unix
                   15683:    timestamp by 1 until a unique key is obtained.
                   15684: 
                   15685: 7. who: holder of locking key; defaults to user:domain for user.
                   15686: 
                   15687: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15688:    retrying); default is 3.
                   15689: 
                   15690: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15691: 
                   15692: Returns:
                   15693: 
                   15694: 1. suffix obtained (numeric)
                   15695: 
                   15696: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15697: 
                   15698: 3. error: contains (localized) error message if an error occurred.
                   15699: 
1.747     albertel 15700: 
1.608     albertel 15701: =back
                   15702: 
1.243     albertel 15703: =head2 HTTP Helper Routines
                   15704: 
                   15705: =over 4
                   15706: 
1.191     harris41 15707: =item *
                   15708: 
                   15709: escape() : unpack non-word characters into CGI-compatible hex codes
                   15710: 
                   15711: =item *
                   15712: 
                   15713: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15714: 
1.243     albertel 15715: =back
                   15716: 
                   15717: =head1 PRIVATE SUBROUTINES
                   15718: 
                   15719: =head2 Underlying communication routines (Shouldn't call)
                   15720: 
                   15721: =over 4
                   15722: 
                   15723: =item *
                   15724: 
                   15725: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15726: 
                   15727: =item *
                   15728: 
                   15729: reply() : uses subreply to send a message to remote machine, logs all failures
                   15730: 
                   15731: =item *
                   15732: 
                   15733: critical() : passes a critical message to another server; if cannot
                   15734: get through then place message in connection buffer directory and
                   15735: returns con_delayed, if incapable of saving message, returns
                   15736: con_failed
                   15737: 
                   15738: =item *
                   15739: 
                   15740: reconlonc() : tries to reconnect lonc client processes.
                   15741: 
                   15742: =back
                   15743: 
                   15744: =head2 Resource Access Logging
                   15745: 
                   15746: =over 4
                   15747: 
                   15748: =item *
                   15749: 
                   15750: flushcourselogs() : flush (save) buffer logs and access logs
                   15751: 
                   15752: =item *
                   15753: 
                   15754: courselog($what) : save message for course in hash
                   15755: 
                   15756: =item *
                   15757: 
                   15758: courseacclog($what) : save message for course using &courselog().  Perform
                   15759: special processing for specific resource types (problems, exams, quizzes, etc).
                   15760: 
1.191     harris41 15761: =item *
                   15762: 
                   15763: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15764: as a PerlChildExitHandler
1.243     albertel 15765: 
                   15766: =back
                   15767: 
                   15768: =head2 Other
                   15769: 
                   15770: =over 4
                   15771: 
                   15772: =item *
                   15773: 
                   15774: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15775: 
                   15776: =back
                   15777: 
                   15778: =cut
1.877     foxr     15779: 

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