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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.139! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.138 2021/02/07 21:33:09 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.134  raeburn   128:         my $ip = &get_requestor_ip();  
1.1172.2.9  raeburn   129:         my $logentry = {
                    130:                          $id => {
                    131:                                   'exe_uname' => $env{'user.name'},
                    132:                                   'exe_udom'  => $env{'user.domain'},
                    133:                                   'exe_time'  => $now,
1.1172.2.134  raeburn   134:                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   135:                                   'delflag'   => $delflag,
                    136:                                   'logentry'  => $storehash,
                    137:                                   'uname'     => $uname,
                    138:                                   'udom'      => $udom,
                    139:                                 }
                    140:                        };
                    141:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       142:     }
                    143: }
1.1       albertel  144: 
1.163     harris41  145: sub logtouch {
                    146:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  147:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   148: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  149: 	close $fh;
                    150:     }
                    151:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    152:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    153: }
                    154: 
1.1       albertel  155: sub logthis {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.1172.2.96  raeburn   160:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      161: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    162: 	print $fh $logstring;
1.448     albertel  163: 	close($fh);
                    164:     }
1.1       albertel  165:     return 1;
                    166: }
                    167: 
                    168: sub logperm {
                    169:     my $message=shift;
                    170:     my $execdir=$perlvar{'lonDaemons'};
                    171:     my $now=time;
                    172:     my $local=localtime($now);
1.1172.2.96  raeburn   173:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  174: 	print $fh "$now:$message:$local\n";
                    175: 	close($fh);
                    176:     }
1.1       albertel  177:     return 1;
                    178: }
                    179: 
1.850     albertel  180: sub create_connection {
1.853     albertel  181:     my ($hostname,$lonid) = @_;
1.851     albertel  182:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  183: 				     Type    => SOCK_STREAM,
                    184: 				     Timeout => 10);
                    185:     return 0 if (!$client);
1.890     albertel  186:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  187:     my $result = <$client>;
                    188:     chomp($result);
                    189:     return 1 if ($result eq 'done');
                    190:     return 0;
                    191: }
                    192: 
1.983     raeburn   193: sub get_server_timezone {
                    194:     my ($cnum,$cdom) = @_;
                    195:     my $home=&homeserver($cnum,$cdom);
                    196:     if ($home ne 'no_host') {
                    197:         my $cachetime = 24*3600;
                    198:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    199:         if (defined($cached)) {
                    200:             return $timezone;
                    201:         } else {
                    202:             my $timezone = &reply('servertimezone',$home);
                    203:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    204:         }
                    205:     }
                    206: }
1.850     albertel  207: 
1.1106    raeburn   208: sub get_server_distarch {
                    209:     my ($lonhost,$ignore_cache) = @_;
                    210:     if (defined($lonhost)) {
                    211:         if (!defined(&hostname($lonhost))) {
                    212:             return;
                    213:         }
                    214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $distarch;
                    219:             }
                    220:         }
                    221:         my $rep = &reply('serverdistarch',$lonhost);
                    222:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    223:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    224:                 $rep eq '') {
                    225:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    226:         }
                    227:     }
                    228:     return;
                    229: }
                    230: 
1.993     raeburn   231: sub get_server_loncaparev {
1.1073    raeburn   232:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   233:     if (defined($lonhost)) {
                    234:         if (!defined(&hostname($lonhost))) {
                    235:             undef($lonhost);
                    236:         }
                    237:     }
                    238:     if (!defined($lonhost)) {
                    239:         if (defined(&domain($dom,'primary'))) {
                    240:             $lonhost=&domain($dom,'primary');
                    241:             if ($lonhost eq 'no_host') {
                    242:                 undef($lonhost);
                    243:             }
                    244:         }
                    245:     }
                    246:     if (defined($lonhost)) {
1.1073    raeburn   247:         my $cachetime = 12*3600;
                    248:         if (!$ignore_cache) {
                    249:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    250:             if (defined($cached)) {
                    251:                 return $loncaparev;
                    252:             }
                    253:         }
                    254:         my ($answer,$loncaparev);
                    255:         my @ids=&current_machine_ids();
                    256:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    257:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   258:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   259:                 $loncaparev = $1;
                    260:             }
                    261:         } else {
                    262:             $answer = &reply('serverloncaparev',$lonhost);
                    263:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    264:                 if ($caller eq 'loncron') {
                    265:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   266:                     $ua->timeout(4);
1.1172.2.120  raeburn   267:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   270:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1172.2.35  raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364: }
                    365: 
1.1       albertel  366: # -------------------------------------------------- Non-critical communication
                    367: sub subreply {
                    368:     my ($cmd,$server)=@_;
1.838     albertel  369:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      370:     #
                    371:     #  With loncnew process trimming, there's a timing hole between lonc server
                    372:     #  process exit and the master server picking up the listen on the AF_UNIX
                    373:     #  socket.  In that time interval, a lock file will exist:
                    374: 
                    375:     my $lockfile=$peerfile.".lock";
                    376:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   377: 	sleep(0.1);
1.549     foxr      378:     }
                    379:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      380:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      381:     #
1.550     foxr      382:     #   We'll give the connection a few tries before abandoning it.  If
                    383:     #   connection is not possible, we'll con_lost back to the client.
                    384:     #   
                    385:     my $client;
                    386:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    387: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    388: 				      Type    => SOCK_STREAM,
                    389: 				      Timeout => 10);
1.869     albertel  390: 	if ($client) {
1.550     foxr      391: 	    last;		# Connected!
1.850     albertel  392: 	} else {
1.853     albertel  393: 	    &create_connection(&hostname($server),$server);
1.550     foxr      394: 	}
1.1172.2.79  raeburn   395:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      396:     }
                    397:     my $answer;
                    398:     if ($client) {
1.704     albertel  399: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      400: 	$answer=<$client>;
                    401: 	if (!$answer) { $answer="con_lost"; }
                    402: 	chomp($answer);
                    403:     } else {
                    404: 	$answer = 'con_lost';	# Failed connection.
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: sub reply {
                    410:     my ($cmd,$server)=@_;
1.838     albertel  411:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  412:     my $answer=subreply($cmd,$server);
1.65      www       413:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   414:         my $logged = $cmd;
                    415:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    416:             my $subcmd = $1;
                    417:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    418:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    419:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    420:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    421:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    422:                     splice(@rest,2,1,'Hidden');
                    423:                 } elsif ($subcmd eq 'passwd') {
                    424:                     splice(@rest,2,2,('Hidden','Hidden'));
                    425:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    426:                          ($subcmd eq 'autoexportgrades')) {
                    427:                     splice(@rest,3,1,'Hidden');
                    428:                 }
                    429:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    430:             }
                    431:         }
                    432:         &logthis("<font color=\"blue\">WARNING:".
                    433:                  " $logged to $server returned $answer</font>");
1.12      www       434:     }
1.1       albertel  435:     return $answer;
                    436: }
                    437: 
                    438: # ----------------------------------------------------------- Send USR1 to lonc
                    439: 
                    440: sub reconlonc {
1.891     albertel  441:     my ($lonid) = @_;
                    442:     if ($lonid) {
1.1172.2.72  raeburn   443:         my $hostname = &hostname($lonid);
1.891     albertel  444: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    445: 	if ($hostname && -e $peerfile) {
                    446: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    447: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    448: 					     Type    => SOCK_STREAM,
                    449: 					     Timeout => 10);
                    450: 	    if ($client) {
                    451: 		print $client ("reset_retries\n");
                    452: 		my $answer=<$client>;
                    453: 		#reset just this one.
                    454: 	    }
                    455: 	}
                    456: 	return;
                    457:     }
                    458: 
1.836     www       459:     &logthis("Trying to reconnect lonc");
1.1       albertel  460:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   461:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  462: 	my $loncpid=<$fh>;
                    463:         chomp($loncpid);
                    464:         if (kill 0 => $loncpid) {
                    465: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    466:             kill USR1 => $loncpid;
                    467:             sleep 1;
1.836     www       468:          } else {
1.12      www       469: 	    &logthis(
1.672     albertel  470:                "<font color=\"blue\">WARNING:".
1.12      www       471:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  472:         }
                    473:     } else {
1.836     www       474: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  475:     }
                    476: }
                    477: 
                    478: # ------------------------------------------------------ Critical communication
1.12      www       479: 
1.1       albertel  480: sub critical {
                    481:     my ($cmd,$server)=@_;
1.838     albertel  482:     unless (&hostname($server)) {
1.672     albertel  483:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       484:                " Critical message to unknown server ($server)</font>");
                    485:         return 'no_such_host';
                    486:     }
1.1       albertel  487:     my $answer=reply($cmd,$server);
                    488:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   489: 	&reconlonc($server);
1.589     albertel  490: 	my $answer=reply($cmd,$server);
1.1       albertel  491:         if ($answer eq 'con_lost') {
                    492:             my $now=time;
                    493:             my $middlename=$cmd;
1.5       www       494:             $middlename=substr($middlename,0,16);
1.1       albertel  495:             $middlename=~s/\W//g;
                    496:             my $dfilename=
1.305     www       497:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    498:             $dumpcount++;
1.1       albertel  499:             {
1.448     albertel  500: 		my $dfh;
1.1172.2.96  raeburn   501: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  502: 		    print $dfh "$cmd\n"; 
                    503: 		    close($dfh);
                    504: 		}
1.1       albertel  505:             }
1.1172.2.79  raeburn   506:             sleep 1;
1.1       albertel  507:             my $wcmd='';
                    508:             {
1.448     albertel  509: 		my $dfh;
1.1172.2.96  raeburn   510: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  511: 		    $wcmd=<$dfh>; 
                    512: 		    close($dfh);
                    513: 		}
1.1       albertel  514:             }
                    515:             chomp($wcmd);
1.7       www       516:             if ($wcmd eq $cmd) {
1.672     albertel  517: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       518:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  519:                 &logperm("D:$server:$cmd");
                    520: 	        return 'con_delayed';
                    521:             } else {
1.672     albertel  522:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       523:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  524:                 &logperm("F:$server:$cmd");
                    525:                 return 'con_failed';
                    526:             }
                    527:         }
                    528:     }
                    529:     return $answer;
1.405     albertel  530: }
                    531: 
1.755     albertel  532: # ------------------------------------------- check if return value is an error
                    533: 
                    534: sub error {
                    535:     my ($result) = @_;
1.756     albertel  536:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  537: 	if ($2 == 2) { return undef; }
                    538: 	return $1;
                    539:     }
                    540:     return undef;
                    541: }
                    542: 
1.783     albertel  543: sub convert_and_load_session_env {
                    544:     my ($lonidsdir,$handle)=@_;
                    545:     my @profile;
                    546:     {
1.917     albertel  547: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    548: 	if (!$opened) {
1.915     albertel  549: 	    return 0;
                    550: 	}
1.783     albertel  551: 	flock($idf,LOCK_SH);
                    552: 	@profile=<$idf>;
                    553: 	close($idf);
                    554:     }
                    555:     my %temp_env;
                    556:     foreach my $line (@profile) {
1.786     albertel  557: 	if ($line !~ m/=/) {
                    558: 	    return 0;
                    559: 	}
1.783     albertel  560: 	chomp($line);
                    561: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    562: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    563:     }
                    564:     unlink("$lonidsdir/$handle.id");
                    565:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    566: 	    0640)) {
                    567: 	%disk_env = %temp_env;
                    568: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    569: 	untie(%disk_env);
                    570:     }
1.786     albertel  571:     return 1;
1.783     albertel  572: }
                    573: 
1.374     www       574: # ------------------------------------------- Transfer profile into environment
1.780     albertel  575: my $env_loaded;
                    576: sub transfer_profile_to_env {
1.788     albertel  577:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    578:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       579: 
1.720     albertel  580:     if (!defined($lonidsdir)) {
                    581: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    582:     }
                    583:     if (!defined($handle)) {
                    584:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    585:     }
                    586: 
1.786     albertel  587:     my $convert;
                    588:     {
1.917     albertel  589:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    590: 	if (!$opened) {
1.915     albertel  591: 	    return;
                    592: 	}
1.786     albertel  593: 	flock($idf,LOCK_SH);
                    594: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    595: 		&GDBM_READER(),0640)) {
                    596: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    597: 	    untie(%disk_env);
                    598: 	} else {
                    599: 	    $convert = 1;
                    600: 	}
                    601:     }
                    602:     if ($convert) {
                    603: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    604: 	    &logthis("Failed to load session, or convert session.");
                    605: 	}
1.374     www       606:     }
1.783     albertel  607: 
1.786     albertel  608:     my %remove;
1.783     albertel  609:     while ( my $envname = each(%env) ) {
1.433     matthew   610:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    611:             if ($time < time-300) {
1.783     albertel  612:                 $remove{$key}++;
1.433     matthew   613:             }
                    614:         }
                    615:     }
1.783     albertel  616: 
1.619     albertel  617:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  618:     $env_loaded=1;
1.783     albertel  619:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   620:         &delenv($expired_key);
1.374     www       621:     }
1.1       albertel  622: }
                    623: 
1.916     albertel  624: # ---------------------------------------------------- Check for valid session 
                    625: sub check_for_valid_session {
1.1172.2.96  raeburn   626:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  627:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   628:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   629:     if ($name eq 'lonDAV') {
                    630:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    631:     } else {
                    632:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   633:         if ($name eq '') {
                    634:             $name = 'lonID';
                    635:         }
                    636:     }
                    637:     if ($name eq 'lonID') {
                    638:         $secure = 'lonSID';
                    639:         $linkname = 'lonLinkID';
                    640:         $pubname = 'lonPubID';
                    641:         if (exists($cookies{$secure})) {
                    642:             $lonid=$cookies{$secure};
                    643:         } elsif (exists($cookies{$name})) {
                    644:             $lonid=$cookies{$name};
                    645:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    646:             $lonid=$cookies{$linkname};
                    647:         } elsif (exists($cookies{$pubname})) {
                    648:             $lonid=$cookies{$pubname};
                    649:         }
                    650:     } else {
                    651:         $lonid=$cookies{$name};
                    652:     }
                    653:     return undef if (!$lonid);
                    654: 
                    655:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    656:     if (-l "$lonidsdir/$handle.id") {
                    657:         my $link = readlink("$lonidsdir/$handle.id");
                    658:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    659:             $handle = $1;
                    660:         }
1.1155    raeburn   661:     }
1.1172.2.96  raeburn   662:     if (!-e "$lonidsdir/$handle.id") {
                    663:         if ((ref($domref)) && ($name eq 'lonID') &&
                    664:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    665:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    666:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    667:                 $$domref = $possudom;
                    668:             }
                    669:         }
                    670:         return undef;
                    671:     }
1.916     albertel  672: 
1.917     albertel  673:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    674:     return undef if (!$opened);
1.916     albertel  675: 
                    676:     flock($idf,LOCK_SH);
                    677:     my %disk_env;
                    678:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    679: 	    &GDBM_READER(),0640)) {
                    680: 	return undef;	
                    681:     }
                    682: 
                    683:     if (!defined($disk_env{'user.name'})
                    684: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   685:         untie(%disk_env);
1.916     albertel  686: 	return undef;
                    687:     }
1.1172.2.18  raeburn   688: 
1.1172.2.36  raeburn   689:     if (ref($userhashref) eq 'HASH') {
                    690:         $userhashref->{'name'} = $disk_env{'user.name'};
                    691:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   692:     }
1.1172.2.107  raeburn   693:     untie(%disk_env);
1.1172.2.18  raeburn   694: 
1.916     albertel  695:     return $handle;
                    696: }
                    697: 
1.830     albertel  698: sub timed_flock {
                    699:     my ($file,$lock_type) = @_;
                    700:     my $failed=0;
                    701:     eval {
                    702: 	local $SIG{__DIE__}='DEFAULT';
                    703: 	local $SIG{ALRM}=sub {
                    704: 	    $failed=1;
                    705: 	    die("failed lock");
                    706: 	};
                    707: 	alarm(13);
                    708: 	flock($file,$lock_type);
                    709: 	alarm(0);
                    710:     };
                    711:     if ($failed) {
                    712: 	return undef;
                    713:     } else {
                    714: 	return 1;
                    715:     }
                    716: }
                    717: 
1.1172.2.107  raeburn   718: sub get_sessionfile_vars {
                    719:     my ($handle,$lonidsdir,$storearr) = @_;
                    720:     my %returnhash;
                    721:     unless (ref($storearr) eq 'ARRAY') {
                    722:         return %returnhash;
                    723:     }
                    724:     if (-l "$lonidsdir/$handle.id") {
                    725:         my $link = readlink("$lonidsdir/$handle.id");
                    726:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    727:             $handle = $1;
                    728:         }
                    729:     }
                    730:     if ((-e "$lonidsdir/$handle.id") &&
                    731:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    732:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    733:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    734:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    735:                 flock($idf,LOCK_SH);
                    736:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    737:                         &GDBM_READER(),0640)) {
                    738:                     foreach my $item (@{$storearr}) {
                    739:                         $returnhash{$item} = $disk_env{$item};
                    740:                     }
                    741:                     untie(%disk_env);
                    742:                 }
                    743:             }
                    744:         }
                    745:     }
                    746:     return %returnhash;
                    747: }
                    748: 
1.5       www       749: # ---------------------------------------------------------- Append Environment
                    750: 
                    751: sub appenv {
1.949     raeburn   752:     my ($newenv,$roles) = @_;
                    753:     if (ref($newenv) eq 'HASH') {
                    754:         foreach my $key (keys(%{$newenv})) {
                    755:             my $refused = 0;
                    756: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    757:                 $refused = 1;
                    758:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   759:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   760:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    761:                         $refused = 0;
                    762:                     }
                    763:                 }
                    764:             }
                    765:             if ($refused) {
                    766:                 &logthis("<font color=\"blue\">WARNING: ".
                    767:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    768:                          .'</font>');
                    769: 	        delete($newenv->{$key});
                    770:             } else {
                    771:                 $env{$key}=$newenv->{$key};
                    772:             }
                    773:         }
1.1172.2.96  raeburn   774:         my $lonids = $perlvar{'lonIDsDir'};
                    775:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    776:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    777:             if ($opened
                    778: 	        && &timed_flock($env_file,LOCK_EX)
                    779: 	        &&
                    780: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    781: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    782: 	        while (my ($key,$value) = each(%{$newenv})) {
                    783: 	            $disk_env{$key} = $value;
                    784: 	        }
                    785: 	        untie(%disk_env);
                    786:             }
1.35      www       787:         }
1.191     harris41  788:     }
1.56      www       789:     return 'ok';
                    790: }
                    791: # ----------------------------------------------------- Delete from Environment
                    792: 
                    793: sub delenv {
1.1104    raeburn   794:     my ($delthis,$regexp,$roles) = @_;
                    795:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    796:         my $refused = 1;
                    797:         if (ref($roles) eq 'ARRAY') {
                    798:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    799:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    800:                 $refused = 0;
                    801:             }
                    802:         }
                    803:         if ($refused) {
                    804:             &logthis("<font color=\"blue\">WARNING: ".
                    805:                      "Attempt to delete from environment ".$delthis);
                    806:             return 'error';
                    807:         }
1.56      www       808:     }
1.917     albertel  809:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    810:     if ($opened
1.915     albertel  811: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  812: 	&&
                    813: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    814: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  815: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   816: 	    if ($regexp) {
                    817:                 if ($key=~/^$delthis/) {
                    818:                     delete($env{$key});
                    819:                     delete($disk_env{$key});
                    820:                 } 
                    821:             } else {
                    822:                 if ($key=~/^\Q$delthis\E/) {
                    823: 		    delete($env{$key});
                    824: 		    delete($disk_env{$key});
                    825: 	        }
                    826:             }
1.448     albertel  827: 	}
1.783     albertel  828: 	untie(%disk_env);
1.5       www       829:     }
                    830:     return 'ok';
1.369     albertel  831: }
                    832: 
1.790     albertel  833: sub get_env_multiple {
                    834:     my ($name) = @_;
                    835:     my @values;
                    836:     if (defined($env{$name})) {
                    837:         # exists is it an array
                    838:         if (ref($env{$name})) {
                    839:             @values=@{ $env{$name} };
                    840:         } else {
                    841:             $values[0]=$env{$name};
                    842:         }
                    843:     }
                    844:     return(@values);
                    845: }
                    846: 
1.958     www       847: # ------------------------------------------------------------------- Locking
                    848: 
                    849: sub set_lock {
                    850:     my ($text)=@_;
                    851:     $locknum++;
                    852:     my $id=$$.'-'.$locknum;
                    853:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    854:              'session.lock.'.$id => $text});
                    855:     return $id;
                    856: }
                    857: 
                    858: sub get_locks {
                    859:     my $num=0;
                    860:     my %texts=();
                    861:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    862:        if ($lock=~/\w/) {
                    863:           $num++;
                    864:           $texts{$lock}=$env{'session.lock.'.$lock};
                    865:        }
                    866:    }
                    867:    return ($num,%texts);
                    868: }
                    869: 
                    870: sub remove_lock {
                    871:     my ($id)=@_;
                    872:     my $newlocks='';
                    873:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    874:        if (($lock=~/\w/) && ($lock ne $id)) {
                    875:           $newlocks.=','.$lock;
                    876:        }
                    877:     }
                    878:     &appenv({'session.locks' => $newlocks});
                    879:     &delenv('session.lock.'.$id);
                    880: }
                    881: 
                    882: sub remove_all_locks {
                    883:     my $activelocks=$env{'session.locks'};
                    884:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    885:        if ($lock=~/\w/) {
                    886:           &remove_lock($lock);
                    887:        }
                    888:     }
                    889: }
                    890: 
                    891: 
1.369     albertel  892: # ------------------------------------------ Find out current server userload
                    893: sub userload {
                    894:     my $numusers=0;
                    895:     {
                    896: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    897: 	my $filename;
                    898: 	my $curtime=time;
                    899: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  900: 	    next if ($filename eq '.' || $filename eq '..');
                    901: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   902:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  905: 	}
                    906: 	closedir(LONIDS);
                    907:     }
                    908:     my $userloadpercent=0;
                    909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    910:     if ($maxuserload) {
1.371     albertel  911: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  912:     }
1.372     albertel  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  914:     return $userloadpercent;
1.283     www       915: }
                    916: 
1.1       albertel  917: # ------------------------------ Find server with least workload from spare.tab
1.11      www       918: 
1.1       albertel  919: sub spareserver {
1.1083    raeburn   920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  921:     my $spare_server;
1.370     albertel  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    924:                                                      :  $userloadpercent;
1.1083    raeburn   925:     my ($uint_dom,$remotesessions);
                    926:     if (($udom ne '') && (&domain($udom) ne '')) {
                    927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    930:         $remotesessions = $udomdefaults{'remotesessions'};
                    931:     }
1.1123    raeburn   932:     my $spareshash = &this_host_spares($udom);
                    933:     if (ref($spareshash) eq 'HASH') {
                    934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    937:                                              $try_server));
1.1123    raeburn   938: 	        ($spare_server, $lowest_load) =
                    939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    940:             }
1.1083    raeburn   941:         }
1.784     albertel  942: 
1.1123    raeburn   943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    944: 
                    945:         if (!$found_server) {
                    946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   948:                     next unless (&spare_can_host($udom,$uint_dom,
                    949:                                                  $remotesessions,$try_server));
1.1123    raeburn   950: 	            ($spare_server, $lowest_load) =
                    951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    952:                 }
                    953: 	    }
                    954:         }
1.784     albertel  955:     }
                    956: 
                    957:     if (!$want_server_name) {
1.1001    raeburn   958:         if (defined($spare_server)) {
                    959:             my $hostname = &hostname($spare_server);
1.1083    raeburn   960:             if (defined($hostname)) {
1.1172.2.120  raeburn   961:                 my $protocol = 'http';
                    962:                 if ($protocol{$spare_server} eq 'https') {
                    963:                     $protocol = $protocol{$spare_server};
                    964:                 }
1.1001    raeburn   965: 	        $spare_server = $protocol.'://'.$hostname;
                    966:             }
                    967:         }
1.784     albertel  968:     }
                    969:     return $spare_server;
                    970: }
                    971: 
                    972: sub compare_server_load {
1.1172.2.41  raeburn   973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    974: 
                    975:     if ($required) {
                    976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    979:         if (($major eq '' && $minor eq '') ||
                    980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    981:             return ($spare_server,$lowest_load);
                    982:         }
                    983:     }
1.784     albertel  984: 
                    985:     my $loadans     = &reply('load',    $try_server);
                    986:     my $userloadans = &reply('userload',$try_server);
                    987: 
                    988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  990:     }
                    991: 
                    992:     my $load;
                    993:     if ($loadans =~ /\d/) {
                    994: 	if ($userloadans =~ /\d/) {
                    995: 	    #both are numbers, pick the bigger one
                    996: 	    $load = ($loadans > $userloadans) ? $loadans 
                    997: 		                              : $userloadans;
1.411     albertel  998: 	} else {
1.784     albertel  999: 	    $load = $loadans;
1.411     albertel 1000: 	}
1.784     albertel 1001:     } else {
                   1002: 	$load = $userloadans;
                   1003:     }
                   1004: 
                   1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1006: 	$spare_server = $try_server;
                   1007: 	$lowest_load  = $load;
1.370     albertel 1008:     }
1.784     albertel 1009:     return ($spare_server,$lowest_load);
1.202     matthew  1010: }
1.914     albertel 1011: 
                   1012: # --------------------------- ask offload servers if user already has a session
                   1013: sub find_existing_session {
                   1014:     my ($udom,$uname) = @_;
1.1123    raeburn  1015:     my $spareshash = &this_host_spares($udom);
                   1016:     if (ref($spareshash) eq 'HASH') {
                   1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1020:             }
                   1021:         }
                   1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1025:             }
                   1026:         }
1.914     albertel 1027:     }
                   1028:     return;
                   1029: }
                   1030: 
1.1172.2.107  raeburn  1031: # check if user's browser sent load balancer cookie and server still has session
                   1032: # and is not overloaded.
                   1033: sub check_for_balancer_cookie {
                   1034:     my ($r,$update_mtime) = @_;
                   1035:     my ($otherserver,$cookie);
                   1036:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1037:     if (exists($cookies{'balanceID'})) {
                   1038:         my $balid = $cookies{'balanceID'};
                   1039:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1040:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1041:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1042:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1043:                 my ($possudom,$possuname) = ($1,$2);
                   1044:                 my $has_session = 0;
                   1045:                 if ((&domain($possudom) ne '') &&
                   1046:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1047:                     my $try_server;
                   1048:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1049:                     if ($opened) {
                   1050:                         flock($idf,LOCK_SH);
                   1051:                         while (my $line = <$idf>) {
                   1052:                             chomp($line);
                   1053:                             if (&hostname($line) ne '') {
                   1054:                                 $try_server = $line;
                   1055:                                 last;
                   1056:                             }
                   1057:                         }
                   1058:                         close($idf);
                   1059:                         if (($try_server) &&
                   1060:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1061:                             my $lowest_load = 30000;
                   1062:                             ($otherserver,$lowest_load) =
                   1063:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1064:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1065:                                 $has_session = 1;
                   1066:                             } else {
                   1067:                                 undef($otherserver);
                   1068:                             }
                   1069:                         }
                   1070:                     }
                   1071:                 }
                   1072:                 if ($has_session) {
                   1073:                     if ($update_mtime) {
                   1074:                         my $atime = my $mtime = time;
                   1075:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1076:                     }
                   1077:                 } else {
                   1078:                     unlink("$balancedir/$cookie.id");
                   1079:                 }
                   1080:             }
                   1081:         }
                   1082:     }
                   1083:     return ($otherserver,$cookie);
                   1084: }
                   1085: 
1.1172.2.130  raeburn  1086: sub updatebalcookie {
                   1087:     my ($cookie,$balancer,$lastentry)=@_;
                   1088:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1089:         my ($udom,$uname) = ($1,$2);
                   1090:         my $uprimary_id = &domain($udom,'primary');
                   1091:         my $uintdom = &internet_dom($uprimary_id);
                   1092:         my $intdom = &internet_dom($balancer);
                   1093:         my $serverhomedom = &host_domain($balancer);
                   1094:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1095:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1096:         }
                   1097:     }
                   1098:     return;
                   1099: }
                   1100: 
1.1172.2.107  raeburn  1101: sub delbalcookie {
                   1102:     my ($cookie,$balancer) =@_;
                   1103:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1104:         my ($udom,$uname) = ($1,$2);
                   1105:         my $uprimary_id = &domain($udom,'primary');
                   1106:         my $uintdom = &internet_dom($uprimary_id);
                   1107:         my $intdom = &internet_dom($balancer);
                   1108:         my $serverhomedom = &host_domain($balancer);
                   1109:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130  raeburn  1110:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1111:         }
                   1112:     }
                   1113: }
                   1114: 
1.914     albertel 1115: # -------------------------------- ask if server already has a session for user
                   1116: sub has_user_session {
                   1117:     my ($lonid,$udom,$uname) = @_;
                   1118:     my $result = &reply(join(':','userhassession',
                   1119: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1120:     return 1 if ($result eq 'ok');
                   1121: 
                   1122:     return 0;
                   1123: }
                   1124: 
1.1076    raeburn  1125: # --------- determine least loaded server in a user's domain which allows login
                   1126: 
                   1127: sub choose_server {
1.1172.2.47  raeburn  1128:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1129:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1130:     my %servers = &get_servers($udom);
1.1076    raeburn  1131:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1132:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1133:     if ($skiploadbal) {
                   1134:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1135:         unless (defined($cached)) {
                   1136:             my $cachetime = 60*60*24;
                   1137:             my %domconfig =
                   1138:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1139:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1140:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1141:                                            $cachetime);
                   1142:             }
                   1143:         }
                   1144:     }
1.1076    raeburn  1145:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1146:         my $loginvia;
1.1172.2.47  raeburn  1147:         if ($skiploadbal) {
                   1148:             if (ref($balancers) eq 'HASH') {
                   1149:                 next if (exists($balancers->{$lonhost}));
                   1150:             }
                   1151:         }
1.1115    raeburn  1152:         if ($checkloginvia) {
                   1153:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1154:             if ($loginvia) {
                   1155:                 my ($server,$path) = split(/:/,$loginvia);
                   1156:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1157:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1158:                 if ($login_host eq $server) {
                   1159:                     $portal_path = $path;
1.1151    raeburn  1160:                     $isredirect = 1;
1.1116    raeburn  1161:                 }
                   1162:             } else {
                   1163:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1164:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1165:                 if ($login_host eq $lonhost) {
                   1166:                     $portal_path = '';
1.1151    raeburn  1167:                     $isredirect = ''; 
1.1116    raeburn  1168:                 }
                   1169:             }
                   1170:         } else {
1.1076    raeburn  1171:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1172:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1173:         }
                   1174:     }
                   1175:     if ($login_host ne '') {
1.1116    raeburn  1176:         $hostname = &hostname($login_host);
1.1076    raeburn  1177:     }
1.1172.2.88  raeburn  1178:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1179: }
                   1180: 
1.1172.2.123  raeburn  1181: sub get_course_sessions {
                   1182:     my ($cnum,$cdom,$lastactivity) = @_;
                   1183:     my %servers = &internet_dom_servers($cdom);
                   1184:     my %returnhash;
                   1185:     foreach my $server (sort(keys(%servers))) {
                   1186:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1187:         my @pairs=split(/\&/,$rep);
                   1188:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1189:             foreach my $item (@pairs) {
                   1190:                 my ($key,$value)=split(/=/,$item,2);
                   1191:                 $key = &unescape($key);
                   1192:                 next if ($key =~ /^error: 2 /);
                   1193:                 if (exists($returnhash{$key})) {
                   1194:                     next if ($value < $returnhash{$key});
                   1195:                 }
                   1196:                 $returnhash{$key}=$value;
                   1197:             }
                   1198:         }
                   1199:     }
                   1200:     return %returnhash;
                   1201: }
                   1202: 
1.202     matthew  1203: # --------------------------------------------- Try to change a user's password
                   1204: 
                   1205: sub changepass {
1.799     raeburn  1206:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1207:     $currentpass = &escape($currentpass);
                   1208:     $newpass     = &escape($newpass);
1.1030    raeburn  1209:     my $lonhost = $perlvar{'lonHostID'};
                   1210:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1211: 		       $server);
                   1212:     if (! $answer) {
                   1213: 	&logthis("No reply on password change request to $server ".
                   1214: 		 "by $uname in domain $udom.");
                   1215:     } elsif ($answer =~ "^ok") {
                   1216:         &logthis("$uname in $udom successfully changed their password ".
                   1217: 		 "on $server.");
                   1218:     } elsif ($answer =~ "^pwchange_failure") {
                   1219: 	&logthis("$uname in $udom was unable to change their password ".
                   1220: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1221: 		 "or pwchange");
                   1222:     } elsif ($answer =~ "^non_authorized") {
                   1223:         &logthis("$uname in $udom did not get their password correct when ".
                   1224: 		 "attempting to change it on $server.");
                   1225:     } elsif ($answer =~ "^auth_mode_error") {
                   1226:         &logthis("$uname in $udom attempted to change their password despite ".
                   1227: 		 "not being locally or internally authenticated on $server.");
                   1228:     } elsif ($answer =~ "^unknown_user") {
                   1229:         &logthis("$uname in $udom attempted to change their password ".
                   1230: 		 "on $server but were unable to because $server is not ".
                   1231: 		 "their home server.");
                   1232:     } elsif ($answer =~ "^refused") {
                   1233: 	&logthis("$server refused to change $uname in $udom password because ".
                   1234: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1235:     } elsif ($answer =~ "invalid_client") {
                   1236:         &logthis("$server refused to change $uname in $udom password because ".
                   1237:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1238:     } elsif ($answer =~ "^prioruse") {
                   1239:        &logthis("$server refused to change $uname in $udom password because ".
                   1240:                 "the password had been used before");
1.202     matthew  1241:     }
                   1242:     return $answer;
1.1       albertel 1243: }
                   1244: 
1.169     harris41 1245: # ----------------------- Try to determine user's current authentication scheme
                   1246: 
                   1247: sub queryauthenticate {
                   1248:     my ($uname,$udom)=@_;
1.456     albertel 1249:     my $uhome=&homeserver($uname,$udom);
                   1250:     if (!$uhome) {
                   1251: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1252: 	return 'no_host';
                   1253:     }
                   1254:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1255:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1256: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1257:     }
1.456     albertel 1258:     return $answer;
1.169     harris41 1259: }
                   1260: 
1.1       albertel 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1262: 
1.1       albertel 1263: sub authenticate {
1.1073    raeburn  1264:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1265:     $upass=&escape($upass);
                   1266:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1267:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1268:     my $newhome;
1.836     www      1269:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1270: # Maybe the machine was offline and only re-appeared again recently?
                   1271:         &reconlonc();
                   1272: # One more
1.952     raeburn  1273: 	$uhome=&homeserver($uname,$udom,1);
                   1274:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1275:             if (defined(&domain($udom,'primary'))) {
                   1276:                 $newhome=&domain($udom,'primary');
                   1277:             }
                   1278:             if ($newhome ne '') {
                   1279:                 $uhome = $newhome;
                   1280:             }
                   1281:         }
1.836     www      1282: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1283: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1284: 	    return 'no_host';
                   1285:         }
1.1       albertel 1286:     }
1.1073    raeburn  1287:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1288:     if ($answer eq 'authorized') {
1.952     raeburn  1289:         if ($newhome) {
                   1290:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1291:             return 'no_account_on_host'; 
                   1292:         } else {
                   1293:             &logthis("User $uname at $udom authorized by $uhome");
                   1294:             return $uhome;
                   1295:         }
1.471     albertel 1296:     }
                   1297:     if ($answer eq 'non_authorized') {
                   1298: 	&logthis("User $uname at $udom rejected by $uhome");
                   1299: 	return 'no_host'; 
1.9       www      1300:     }
1.471     albertel 1301:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1302:     return 'no_host';
                   1303: }
                   1304: 
1.1073    raeburn  1305: sub can_host_session {
1.1074    raeburn  1306:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1307:     my $canhost = 1;
1.1074    raeburn  1308:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1309:     if (ref($remotesessions) eq 'HASH') {
                   1310:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1311:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1312:                 $canhost = 0;
                   1313:             } else {
                   1314:                 $canhost = 1;
                   1315:             }
                   1316:         }
                   1317:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1319:                 $canhost = 1;
                   1320:             } else {
                   1321:                 $canhost = 0;
                   1322:             }
                   1323:         }
                   1324:         if ($canhost) {
                   1325:             if ($remotesessions->{'version'} ne '') {
                   1326:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1327:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1328:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1329:                         my $major = $1;
                   1330:                         my $minor = $2;
                   1331:                         if (($major < $reqmajor ) ||
                   1332:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1333:                             $canhost = 0;
                   1334:                         }
                   1335:                     } else {
                   1336:                         $canhost = 0;
                   1337:                     }
                   1338:                 }
                   1339:             }
                   1340:         }
                   1341:     }
                   1342:     if ($canhost) {
                   1343:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1344:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1345:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1346:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1347:                 if (($uint_dom ne '') && 
                   1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1349:                     $canhost = 0;
                   1350:                 } else {
                   1351:                     $canhost = 1;
                   1352:                 }
                   1353:             }
                   1354:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1355:                 if (($uint_dom ne '') && 
                   1356:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1357:                     $canhost = 1;
                   1358:                 } else {
                   1359:                     $canhost = 0;
                   1360:                 }
                   1361:             }
                   1362:         }
                   1363:     }
                   1364:     return $canhost;
                   1365: }
                   1366: 
1.1083    raeburn  1367: sub spare_can_host {
                   1368:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1369:     my $canhost=1;
1.1172.2.62  raeburn  1370:     my $try_server_hostname = &hostname($try_server);
                   1371:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1372:     my $serverhomedom = &host_domain($serverhomeID);
                   1373:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1374:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1375:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1376:             $canhost = 0;
                   1377:         }
                   1378:     }
1.1172.2.136  raeburn  1379:     if ($canhost) {
                   1380:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1381:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1382:                 unless (&shared_institution($udom,$try_server)) {
                   1383:                     $canhost = 0;
                   1384:                 }
                   1385:             }
                   1386:         }
                   1387:     }
1.1172.2.62  raeburn  1388:     if (($canhost) && ($uint_dom)) {
                   1389:         my @intdoms;
                   1390:         my $internet_names = &get_internet_names($try_server);
                   1391:         if (ref($internet_names) eq 'ARRAY') {
                   1392:             @intdoms = @{$internet_names};
                   1393:         }
                   1394:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1395:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1396:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1397:                                          $remotesessions,
                   1398:                                          $defdomdefaults{'hostedsessions'});
                   1399:         }
1.1083    raeburn  1400:     }
                   1401:     return $canhost;
                   1402: }
                   1403: 
1.1123    raeburn  1404: sub this_host_spares {
                   1405:     my ($dom) = @_;
1.1126    raeburn  1406:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1407:     my @hosts = &current_machine_ids();
                   1408:     foreach my $lonhost (@hosts) {
                   1409:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1410:             $dom_in_use = $dom;
                   1411:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1412:             last;
                   1413:         }
                   1414:     }
1.1126    raeburn  1415:     if ($dom_in_use ne '') {
                   1416:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1417:     }
                   1418:     if (ref($result) ne 'HASH') {
                   1419:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1420:         $dom_in_use = &host_domain($lonhost_in_use);
                   1421:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1422:         if (ref($result) ne 'HASH') {
                   1423:             $result = \%spareid;
                   1424:         }
                   1425:     }
                   1426:     return $result;
                   1427: }
                   1428: 
                   1429: sub spares_for_offload  {
                   1430:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1431:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1432:     if (defined($cached)) {
                   1433:         return $result;
                   1434:     } else {
1.1126    raeburn  1435:         my $cachetime = 60*60*24;
                   1436:         my %domconfig =
                   1437:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1438:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1439:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1440:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1441:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1442:                 }
                   1443:             }
                   1444:         }
                   1445:     }
1.1126    raeburn  1446:     return;
1.1123    raeburn  1447: }
                   1448: 
1.1129    raeburn  1449: sub get_lonbalancer_config {
                   1450:     my ($servers) = @_;
                   1451:     my ($currbalancer,$currtargets);
                   1452:     if (ref($servers) eq 'HASH') {
                   1453:         foreach my $server (keys(%{$servers})) {
                   1454:             my %what = (
                   1455:                          spareid => 1,
                   1456:                          perlvar => 1,
                   1457:                        );
                   1458:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1459:             if ($result eq 'ok') {
                   1460:                 if (ref($returnhash) eq 'HASH') {
                   1461:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1462:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1463:                             $currbalancer = $server;
                   1464:                             $currtargets = {};
                   1465:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1466:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1467:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1468:                                 }
                   1469:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1470:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1471:                                 }
                   1472:                             }
                   1473:                             last;
                   1474:                         }
                   1475:                     }
                   1476:                 }
                   1477:             }
                   1478:         }
                   1479:     }
                   1480:     return ($currbalancer,$currtargets);
                   1481: }
                   1482: 
                   1483: sub check_loadbalancing {
1.1172.2.88  raeburn  1484:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1485:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1486:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1487:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1488:     my @hosts = &current_machine_ids();
1.1129    raeburn  1489:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1490:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1491:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1492:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1493:     my $domneedscache; 
1.1129    raeburn  1494:     my $cachetime = 60*60*24;
                   1495: 
                   1496:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1497:         $dom_in_use = $udom;
                   1498:         $homeintdom = 1;
                   1499:     } else {
                   1500:         $dom_in_use = $serverhomedom;
                   1501:     }
                   1502:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1503:     unless (defined($cached)) {
                   1504:         my %domconfig =
                   1505:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1506:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1507:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1508:         } else {
                   1509:             $domneedscache = $dom_in_use;
1.1129    raeburn  1510:         }
                   1511:     }
                   1512:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1513:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1514:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1515:         if ($is_balancer) {
                   1516:             if (ref($currrules) eq 'HASH') {
                   1517:                 if ($homeintdom) {
                   1518:                     if ($uname ne '') {
                   1519:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1520:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1521:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1522:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1523:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1524:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1525:                             }
                   1526:                         }
                   1527:                         if ($rule_in_effect eq '') {
                   1528:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1529:                             if ($userenv{'inststatus'} ne '') {
                   1530:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1531:                                 my ($othertitle,$usertypes,$types) =
                   1532:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1533:                                 if (ref($types) eq 'ARRAY') {
                   1534:                                     foreach my $type (@{$types}) {
                   1535:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1536:                                             if (exists($currrules->{$type})) {
                   1537:                                                 $rule_in_effect = $currrules->{$type};
                   1538:                                             }
                   1539:                                         }
                   1540:                                     }
                   1541:                                 }
                   1542:                             } else {
                   1543:                                 if (exists($currrules->{'default'})) {
                   1544:                                     $rule_in_effect = $currrules->{'default'};
                   1545:                                 }
                   1546:                             }
                   1547:                         }
                   1548:                     } else {
                   1549:                         if (exists($currrules->{'default'})) {
                   1550:                             $rule_in_effect = $currrules->{'default'};
                   1551:                         }
                   1552:                     }
                   1553:                 } else {
                   1554:                     if ($currrules->{'_LC_external'} ne '') {
                   1555:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1556:                     }
                   1557:                 }
                   1558:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1559:                                                        $uname,$udom);
                   1560:             }
                   1561:         }
                   1562:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1563:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1564:         unless (defined($cached)) {
                   1565:             my %domconfig =
                   1566:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1567:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1568:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1569:             } else {
                   1570:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1571:             }
                   1572:         }
                   1573:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1574:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1575:                 &check_balancer_result($result,@hosts);
                   1576:             if ($is_balancer) {
1.1129    raeburn  1577:                 if (ref($currrules) eq 'HASH') {
                   1578:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1579:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1580:                     }
                   1581:                 }
                   1582:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1583:                                                        $uname,$udom);
                   1584:             }
                   1585:         } else {
                   1586:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1587:                 $is_balancer = 1;
                   1588:                 $offloadto = &this_host_spares($dom_in_use);
                   1589:             }
1.1172.2.75  raeburn  1590:             unless (defined($cached)) {
                   1591:                 $domneedscache = $serverhomedom;
                   1592:             }
1.1129    raeburn  1593:         }
                   1594:     } else {
                   1595:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1596:             $is_balancer = 1;
                   1597:             $offloadto = &this_host_spares($dom_in_use);
                   1598:         }
1.1172.2.75  raeburn  1599:         unless (defined($cached)) {
                   1600:             $domneedscache = $serverhomedom;
                   1601:         }
                   1602:     }
                   1603:     if ($domneedscache) {
                   1604:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1605:     }
1.1172.2.130  raeburn  1606:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1607:         my $lowest_load = 30000;
                   1608:         if (ref($offloadto) eq 'HASH') {
                   1609:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1610:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1611:                     ($otherserver,$lowest_load) =
                   1612:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1613:                 }
1.1129    raeburn  1614:             }
1.1172.2.5  raeburn  1615:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1616: 
1.1172.2.5  raeburn  1617:             if (!$found_server) {
                   1618:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1619:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1620:                         ($otherserver,$lowest_load) =
                   1621:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1622:                     }
                   1623:                 }
                   1624:             }
                   1625:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1626:             if (@{$offloadto} == 1) {
                   1627:                 $otherserver = $offloadto->[0];
                   1628:             } elsif (@{$offloadto} > 1) {
                   1629:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1630:                     ($otherserver,$lowest_load) =
                   1631:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1632:                 }
                   1633:             }
                   1634:         }
1.1172.2.88  raeburn  1635:         unless ($caller eq 'login') {
                   1636:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1637:                 $is_balancer = 0;
                   1638:                 if ($uname ne '' && $udom ne '') {
                   1639:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1640:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1641:                                  'user.loadbalcheck.time' => time});
                   1642:                     }
1.1172.2.5  raeburn  1643:                 }
1.1129    raeburn  1644:             }
                   1645:         }
1.1172.2.130  raeburn  1646:     }
                   1647:     if (($is_balancer) && (!$homeintdom)) {
                   1648:         undef($setcookie);
1.1129    raeburn  1649:     }
1.1172.2.107  raeburn  1650:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1651: }
                   1652: 
1.1172.2.12  raeburn  1653: sub check_balancer_result {
                   1654:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1655:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1656:     if (ref($result) eq 'HASH') {
                   1657:         if ($result->{'lonhost'} ne '') {
                   1658:             my $currbalancer = $result->{'lonhost'};
                   1659:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1660:                 $is_balancer = 1;
                   1661:                 $currtargets = $result->{'targets'};
                   1662:                 $currrules = $result->{'rules'};
                   1663:             }
                   1664:         } else {
                   1665:             foreach my $key (keys(%{$result})) {
                   1666:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1667:                     (ref($result->{$key}) eq 'HASH')) {
                   1668:                     $is_balancer = 1;
                   1669:                     $currrules = $result->{$key}{'rules'};
                   1670:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1671:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1672:                     last;
                   1673:                 }
                   1674:             }
                   1675:         }
                   1676:     }
1.1172.2.107  raeburn  1677:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1678: }
                   1679: 
1.1129    raeburn  1680: sub get_loadbalancer_targets {
                   1681:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1682:     my $offloadto;
1.1172.2.4  raeburn  1683:     if ($rule_in_effect eq 'none') {
                   1684:         return [$perlvar{'lonHostID'}];
                   1685:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1686:         $offloadto = $currtargets;
                   1687:     } else {
                   1688:         if ($rule_in_effect eq 'homeserver') {
                   1689:             my $homeserver = &homeserver($uname,$udom);
                   1690:             if ($homeserver ne 'no_host') {
                   1691:                 $offloadto = [$homeserver];
                   1692:             }
                   1693:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1694:             my %domconfig =
                   1695:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1696:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1697:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1698:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1699:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1700:                     }
                   1701:                 }
                   1702:             } else {
1.1172.2.7  raeburn  1703:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1704:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1705:                 if (&hostname($remotebalancer) ne '') {
                   1706:                     $offloadto = [$remotebalancer];
                   1707:                 }
                   1708:             }
                   1709:         } elsif (&hostname($rule_in_effect) ne '') {
                   1710:             $offloadto = [$rule_in_effect];
                   1711:         }
                   1712:     }
                   1713:     return $offloadto;
                   1714: }
                   1715: 
1.1127    raeburn  1716: sub internet_dom_servers {
                   1717:     my ($dom) = @_;
                   1718:     my (%uniqservers,%servers);
                   1719:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1720:     my @machinedoms = &machine_domains($primaryserver);
                   1721:     foreach my $mdom (@machinedoms) {
                   1722:         my %currservers = %servers;
                   1723:         my %server = &get_servers($mdom);
                   1724:         %servers = (%currservers,%server);
                   1725:     }
                   1726:     my %by_hostname;
                   1727:     foreach my $id (keys(%servers)) {
                   1728:         push(@{$by_hostname{$servers{$id}}},$id);
                   1729:     }
                   1730:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1731:         if (@{$by_hostname{$hostname}} > 1) {
                   1732:             my $match = 0;
                   1733:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1734:                 if (&host_domain($id) eq $dom) {
                   1735:                     $uniqservers{$id} = $hostname;
                   1736:                     $match = 1;
                   1737:                 }
                   1738:             }
                   1739:             unless ($match) {
                   1740:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1741:             }
                   1742:         } else {
                   1743:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1744:         }
                   1745:     }
                   1746:     return %uniqservers;
                   1747: }
                   1748: 
1.1       albertel 1749: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1750: 
1.599     albertel 1751: my %homecache;
1.1       albertel 1752: sub homeserver {
1.230     stredwic 1753:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1754:     my $index="$uname:$udom";
1.426     albertel 1755: 
1.599     albertel 1756:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1757: 
                   1758:     my %servers = &get_servers($udom,'library');
                   1759:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1760:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1761: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1762: 
                   1763: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1764: 	if ($answer eq 'found') {
                   1765: 	    delete($badServerCache{$tryserver}); 
                   1766: 	    return $homecache{$index}=$tryserver;
                   1767: 	} elsif ($answer eq 'no_host') {
                   1768: 	    $badServerCache{$tryserver}=1;
                   1769: 	}
1.1       albertel 1770:     }    
                   1771:     return 'no_host';
1.70      www      1772: }
                   1773: 
                   1774: # ------------------------------------- Find the usernames behind a list of IDs
                   1775: 
                   1776: sub idget {
                   1777:     my ($udom,@ids)=@_;
                   1778:     my %returnhash=();
                   1779:     
1.841     albertel 1780:     my %servers = &get_servers($udom,'library');
                   1781:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1782: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1783: 	$idlist=~tr/A-Z/a-z/; 
                   1784: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1785: 	my @answer=();
                   1786: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1787: 	    @answer=split(/\&/,$reply);
                   1788: 	}                    ;
                   1789: 	my $i;
                   1790: 	for ($i=0;$i<=$#ids;$i++) {
                   1791: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1792: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1793: 	    } 
                   1794: 	}
                   1795:     } 
1.70      www      1796:     return %returnhash;
                   1797: }
                   1798: 
                   1799: # ------------------------------------- Find the IDs behind a list of usernames
                   1800: 
                   1801: sub idrget {
                   1802:     my ($udom,@unames)=@_;
                   1803:     my %returnhash=();
1.800     albertel 1804:     foreach my $uname (@unames) {
                   1805:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1806:     }
1.70      www      1807:     return %returnhash;
                   1808: }
                   1809: 
                   1810: # ------------------------------- Store away a list of names and associated IDs
                   1811: 
                   1812: sub idput {
                   1813:     my ($udom,%ids)=@_;
                   1814:     my %servers=();
1.800     albertel 1815:     foreach my $uname (keys(%ids)) {
                   1816: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1817:         my $uhom=&homeserver($uname,$udom);
1.70      www      1818:         if ($uhom ne 'no_host') {
1.800     albertel 1819:             my $id=&escape($ids{$uname});
1.70      www      1820:             $id=~tr/A-Z/a-z/;
1.800     albertel 1821:             my $esc_unam=&escape($uname);
1.70      www      1822: 	    if ($servers{$uhom}) {
1.800     albertel 1823: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1824:             } else {
1.800     albertel 1825:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1826:             }
                   1827:         }
1.191     harris41 1828:     }
1.800     albertel 1829:     foreach my $server (keys(%servers)) {
                   1830:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1831:     }
1.344     www      1832: }
                   1833: 
1.1172.2.30  raeburn  1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1835: 
                   1836: sub iddel {
                   1837:     my ($udom,$idshashref,$uhome)=@_;
                   1838:     my %result=();
                   1839:     unless (ref($idshashref) eq 'HASH') {
                   1840:         return %result;
                   1841:     }
                   1842:     my %servers=();
                   1843:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1844:         my $uhom;
                   1845:         if ($uhome) {
                   1846:             $uhom = $uhome;
                   1847:         } else {
                   1848:             $uhom=&homeserver($uname,$udom);
                   1849:         }
                   1850:         if ($uhom ne 'no_host') {
                   1851:             if ($servers{$uhom}) {
                   1852:                 $servers{$uhom}.='&'.&escape($id);
                   1853:             } else {
                   1854:                 $servers{$uhom}=&escape($id);
                   1855:             }
                   1856:         }
                   1857:     }
                   1858:     foreach my $server (keys(%servers)) {
                   1859:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1860:     }
                   1861:     return %result;
                   1862: }
                   1863: 
1.1023    raeburn  1864: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1865: sub dump_dom {
1.1165    droeschl 1866:     my ($namespace, $udom, $regexp) = @_;
                   1867: 
                   1868:     $udom ||= $env{'user.domain'};
                   1869: 
                   1870:     return () unless $udom;
                   1871: 
                   1872:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1873: }
                   1874: 
1.1023    raeburn  1875: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1876: 
                   1877: sub get_dom {
1.860     raeburn  1878:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1879:     return if ($udom eq 'public');
1.806     raeburn  1880:     my $items='';
                   1881:     foreach my $item (@$storearr) {
                   1882:         $items.=&escape($item).'&';
                   1883:     }
                   1884:     $items=~s/\&$//;
1.860     raeburn  1885:     if (!$udom) {
                   1886:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1887:         return if ($udom eq 'public');
1.860     raeburn  1888:         if (defined(&domain($udom,'primary'))) {
                   1889:             $uhome=&domain($udom,'primary');
                   1890:         } else {
1.874     albertel 1891:             undef($uhome);
1.860     raeburn  1892:         }
                   1893:     } else {
                   1894:         if (!$uhome) {
                   1895:             if (defined(&domain($udom,'primary'))) {
                   1896:                 $uhome=&domain($udom,'primary');
                   1897:             }
                   1898:         }
                   1899:     }
                   1900:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139! raeburn  1901:         my $rep;
        !          1902:         if (grep { $_ eq $uhome } &current_machine_ids()) {
        !          1903:             # domain information is hosted on this machine
        !          1904:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
        !          1905:         } else {        
        !          1906:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
        !          1907:         }
1.866     raeburn  1908:         my %returnhash;
1.875     albertel 1909:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1910:             return %returnhash;
                   1911:         }
1.806     raeburn  1912:         my @pairs=split(/\&/,$rep);
                   1913:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1914:             return @pairs;
                   1915:         }
                   1916:         my $i=0;
                   1917:         foreach my $item (@$storearr) {
                   1918:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1919:             $i++;
                   1920:         }
                   1921:         return %returnhash;
                   1922:     } else {
1.880     banghart 1923:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1924:     }
                   1925: }
                   1926: 
                   1927: # -------------------------------------------- put items in domain db files 
                   1928: 
                   1929: sub put_dom {
1.860     raeburn  1930:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1931:     if (!$udom) {
                   1932:         $udom=$env{'user.domain'};
                   1933:         if (defined(&domain($udom,'primary'))) {
                   1934:             $uhome=&domain($udom,'primary');
                   1935:         } else {
1.874     albertel 1936:             undef($uhome);
1.860     raeburn  1937:         }
                   1938:     } else {
                   1939:         if (!$uhome) {
                   1940:             if (defined(&domain($udom,'primary'))) {
                   1941:                 $uhome=&domain($udom,'primary');
                   1942:             }
                   1943:         }
                   1944:     } 
                   1945:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1946:         my $items='';
                   1947:         foreach my $item (keys(%$storehash)) {
                   1948:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1949:         }
                   1950:         $items=~s/\&$//;
                   1951:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1952:     } else {
1.860     raeburn  1953:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1954:     }
                   1955: }
                   1956: 
1.1023    raeburn  1957: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1958: sub newput_dom {
1.1023    raeburn  1959:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1960:     my $result;
                   1961:     if (!$udom) {
                   1962:         $udom=$env{'user.domain'};
                   1963:     }
1.1023    raeburn  1964:     if ($udom) {
                   1965:         my $uname = &get_domainconfiguser($udom);
                   1966:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1967:     }
                   1968:     return $result;
                   1969: }
                   1970: 
1.1023    raeburn  1971: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1972: sub del_dom {
1.1023    raeburn  1973:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1974:     if (ref($storearr) eq 'ARRAY') {
                   1975:         if (!$udom) {
                   1976:             $udom=$env{'user.domain'};
                   1977:         }
1.1023    raeburn  1978:         if ($udom) {
                   1979:             my $uname = &get_domainconfiguser($udom); 
                   1980:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1981:         }
                   1982:     }
                   1983: }
                   1984: 
1.1023    raeburn  1985: # ----------------------------------construct domainconfig user for a domain 
                   1986: sub get_domainconfiguser {
                   1987:     my ($udom) = @_;
                   1988:     return $udom.'-domainconfig';
                   1989: }
                   1990: 
1.837     raeburn  1991: sub retrieve_inst_usertypes {
                   1992:     my ($udom) = @_;
                   1993:     my (%returnhash,@order);
1.989     raeburn  1994:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1995:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1996:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1997:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1998:     } else {
                   1999:         if (defined(&domain($udom,'primary'))) {
                   2000:             my $uhome=&domain($udom,'primary');
                   2001:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2002:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2003:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2004:                 return (\%returnhash,\@order);
                   2005:             }
                   2006:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2007:             my @pairs=split(/\&/,$hashitems);
                   2008:             foreach my $item (@pairs) {
                   2009:                 my ($key,$value)=split(/=/,$item,2);
                   2010:                 $key = &unescape($key);
                   2011:                 next if ($key =~ /^error: 2 /);
                   2012:                 $returnhash{$key}=&thaw_unescape($value);
                   2013:             }
                   2014:             my @esc_order = split(/\&/,$orderitems);
                   2015:             foreach my $item (@esc_order) {
                   2016:                 push(@order,&unescape($item));
                   2017:             }
                   2018:         } else {
1.1172.2.44  raeburn  2019:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2020:         }
1.1172.2.44  raeburn  2021:         return (\%returnhash,\@order);
1.837     raeburn  2022:     }
                   2023: }
                   2024: 
1.868     raeburn  2025: sub is_domainimage {
                   2026:     my ($url) = @_;
1.1172.2.74  raeburn  2027:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2028:         if (&domain($1) ne '') {
                   2029:             return '1';
                   2030:         }
                   2031:     }
                   2032:     return;
                   2033: }
                   2034: 
1.899     raeburn  2035: sub inst_directory_query {
                   2036:     my ($srch) = @_;
                   2037:     my $udom = $srch->{'srchdomain'};
                   2038:     my %results;
                   2039:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2040:     my $outcome;
1.899     raeburn  2041:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2042:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2043:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2044:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2045:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2046:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2047:                     (($major == 2) && ($minor < 11)) ||
                   2048:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2049:                     return;
                   2050:                 }
                   2051:             }
                   2052:         }
1.904     albertel 2053: 	my $queryid=&reply("querysend:instdirsearch:".
                   2054: 			   &escape($srch->{'srchby'}).':'.
                   2055: 			   &escape($srch->{'srchterm'}).':'.
                   2056: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2057: 	my $host=&hostname($homeserver);
                   2058: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2059: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2060: 	    return;
                   2061: 	}
                   2062: 	my $response = &get_query_reply($queryid);
                   2063: 	my $maxtries = 5;
                   2064: 	my $tries = 1;
                   2065: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2066: 	    $response = &get_query_reply($queryid);
                   2067: 	    $tries ++;
                   2068: 	}
                   2069: 
                   2070:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2071:             if ($response eq 'unavailable') {
                   2072:                 $outcome = $response;
                   2073:             } else {
                   2074:                 $outcome = 'ok';
                   2075:                 my @matches = split(/\n/,$response);
                   2076:                 foreach my $match (@matches) {
                   2077:                     my ($key,$value) = split(/=/,$match);
                   2078:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2079:                 }
1.899     raeburn  2080:             }
                   2081:         }
                   2082:     }
1.909     raeburn  2083:     return ($outcome,%results);
1.899     raeburn  2084: }
                   2085: 
                   2086: sub usersearch {
                   2087:     my ($srch) = @_;
                   2088:     my $dom = $srch->{'srchdomain'};
                   2089:     my %results;
                   2090:     my %libserv = &all_library();
                   2091:     my $query = 'usersearch';
                   2092:     foreach my $tryserver (keys(%libserv)) {
                   2093:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2094:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2095:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2096:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2097:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2098:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2099:                              (($major == 2) && ($minor < 11)) ||
                   2100:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2101:                 }
                   2102:             }
1.899     raeburn  2103:             my $host=&hostname($tryserver);
                   2104:             my $queryid=
1.911     raeburn  2105:                 &reply("querysend:".&escape($query).':'.
                   2106:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2107:                        &escape($srch->{'srchtype'}).':'.
                   2108:                        &escape($srch->{'srchterm'}),$tryserver);
                   2109:             if ($queryid !~/^\Q$host\E\_/) {
                   2110:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2111:                 next;
1.899     raeburn  2112:             }
                   2113:             my $reply = &get_query_reply($queryid);
                   2114:             my $maxtries = 1;
                   2115:             my $tries = 1;
                   2116:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2117:                 $reply = &get_query_reply($queryid);
                   2118:                 $tries ++;
                   2119:             }
                   2120:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2121:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2122:             } else {
1.911     raeburn  2123:                 my @matches;
                   2124:                 if ($reply =~ /\n/) {
                   2125:                     @matches = split(/\n/,$reply);
                   2126:                 } else {
                   2127:                     @matches = split(/\&/,$reply);
                   2128:                 }
1.899     raeburn  2129:                 foreach my $match (@matches) {
                   2130:                     my ($uname,$udom,%userhash);
1.911     raeburn  2131:                     foreach my $entry (split(/:/,$match)) {
                   2132:                         my ($key,$value) =
                   2133:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2134:                         $userhash{$key} = $value;
                   2135:                         if ($key eq 'username') {
                   2136:                             $uname = $value;
                   2137:                         } elsif ($key eq 'domain') {
                   2138:                             $udom = $value;
1.911     raeburn  2139:                         }
1.899     raeburn  2140:                     }
                   2141:                     $results{$uname.':'.$udom} = \%userhash;
                   2142:                 }
                   2143:             }
                   2144:         }
                   2145:     }
                   2146:     return %results;
                   2147: }
                   2148: 
1.912     raeburn  2149: sub get_instuser {
                   2150:     my ($udom,$uname,$id) = @_;
                   2151:     my $homeserver = &domain($udom,'primary');
                   2152:     my ($outcome,%results);
                   2153:     if ($homeserver ne '') {
                   2154:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2155:                            &escape($id).':'.&escape($udom),$homeserver);
                   2156:         my $host=&hostname($homeserver);
                   2157:         if ($queryid !~/^\Q$host\E\_/) {
                   2158:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2159:             return;
                   2160:         }
                   2161:         my $response = &get_query_reply($queryid);
                   2162:         my $maxtries = 5;
                   2163:         my $tries = 1;
                   2164:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2165:             $response = &get_query_reply($queryid);
                   2166:             $tries ++;
                   2167:         }
                   2168:         if (!&error($response) && $response ne 'refused') {
                   2169:             if ($response eq 'unavailable') {
                   2170:                 $outcome = $response;
                   2171:             } else {
                   2172:                 $outcome = 'ok';
                   2173:                 my @matches = split(/\n/,$response);
                   2174:                 foreach my $match (@matches) {
                   2175:                     my ($key,$value) = split(/=/,$match);
                   2176:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2177:                 }
                   2178:             }
                   2179:         }
                   2180:     }
                   2181:     my %userinfo;
                   2182:     if (ref($results{$uname}) eq 'HASH') {
                   2183:         %userinfo = %{$results{$uname}};
                   2184:     } 
                   2185:     return ($outcome,%userinfo);
                   2186: }
                   2187: 
1.1172.2.69  raeburn  2188: sub get_multiple_instusers {
                   2189:     my ($udom,$users,$caller) = @_;
                   2190:     my ($outcome,$results);
                   2191:     if (ref($users) eq 'HASH') {
                   2192:         my $count = keys(%{$users});
                   2193:         my $requested = &freeze_escape($users);
                   2194:         my $homeserver = &domain($udom,'primary');
                   2195:         if ($homeserver ne '') {
                   2196:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2197:             my $host=&hostname($homeserver);
                   2198:             if ($queryid !~/^\Q$host\E\_/) {
                   2199:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2200:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2201:                 return ($outcome,$results);
                   2202:             }
                   2203:             my $response = &get_query_reply($queryid);
                   2204:             my $maxtries = 5;
                   2205:             if ($count > 100) {
                   2206:                 $maxtries = 1+int($count/20);
                   2207:             }
                   2208:             my $tries = 1;
                   2209:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2210:                 $response = &get_query_reply($queryid);
                   2211:                 $tries ++;
                   2212:             }
                   2213:             if ($response eq '') {
                   2214:                 $results = {};
                   2215:                 foreach my $key (keys(%{$users})) {
                   2216:                     my ($uname,$id);
                   2217:                     if ($caller eq 'id') {
                   2218:                         $id = $key;
                   2219:                     } else {
                   2220:                         $uname = $key;
                   2221:                     }
                   2222:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2223:                     $outcome = $resp;
                   2224:                     if ($resp eq 'ok') {
                   2225:                         %{$results} = (%{$results}, %info);
                   2226:                     } else {
                   2227:                         last;
                   2228:                     }
                   2229:                 }
                   2230:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2231:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2232:                     $outcome = $response;
                   2233:                 } else {
                   2234:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2235:                     if ($outcome eq 'ok') {
                   2236:                         $results = &thaw_unescape($userdata);
                   2237:                     }
                   2238:                 }
                   2239:             }
                   2240:         }
                   2241:     }
                   2242:     return ($outcome,$results);
                   2243: }
                   2244: 
1.912     raeburn  2245: sub inst_rulecheck {
1.923     raeburn  2246:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2247:     my %returnhash;
                   2248:     if ($udom ne '') {
                   2249:         if (ref($rules) eq 'ARRAY') {
                   2250:             @{$rules} = map {&escape($_);} (@{$rules});
                   2251:             my $rulestr = join(':',@{$rules});
                   2252:             my $homeserver=&domain($udom,'primary');
                   2253:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2254:                 my $response;
                   2255:                 if ($item eq 'username') {                
                   2256:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2257:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2258:                                               $homeserver));
1.923     raeburn  2259:                 } elsif ($item eq 'id') {
                   2260:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2261:                                               ':'.&escape($id).':'.$rulestr,
                   2262:                                               $homeserver));
1.945     raeburn  2263:                 } elsif ($item eq 'selfcreate') {
                   2264:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2265:                                                &escape($udom).':'.&escape($uname).
                   2266:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2267:                 }
1.912     raeburn  2268:                 if ($response ne 'refused') {
                   2269:                     my @pairs=split(/\&/,$response);
                   2270:                     foreach my $item (@pairs) {
                   2271:                         my ($key,$value)=split(/=/,$item,2);
                   2272:                         $key = &unescape($key);
                   2273:                         next if ($key =~ /^error: 2 /);
                   2274:                         $returnhash{$key}=&thaw_unescape($value);
                   2275:                     }
                   2276:                 }
                   2277:             }
                   2278:         }
                   2279:     }
                   2280:     return %returnhash;
                   2281: }
                   2282: 
                   2283: sub inst_userrules {
1.923     raeburn  2284:     my ($udom,$check) = @_;
1.912     raeburn  2285:     my (%ruleshash,@ruleorder);
                   2286:     if ($udom ne '') {
                   2287:         my $homeserver=&domain($udom,'primary');
                   2288:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2289:             my $response;
                   2290:             if ($check eq 'id') {
                   2291:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2292:                                  $homeserver);
1.943     raeburn  2293:             } elsif ($check eq 'email') {
                   2294:                 $response=&reply('instemailrules:'.&escape($udom),
                   2295:                                  $homeserver);
1.923     raeburn  2296:             } else {
                   2297:                 $response=&reply('instuserrules:'.&escape($udom),
                   2298:                                  $homeserver);
                   2299:             }
1.912     raeburn  2300:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2301:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2302:                 ($response ne 'no_such_host')) {
                   2303:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2304:                 my @pairs=split(/\&/,$hashitems);
                   2305:                 foreach my $item (@pairs) {
                   2306:                     my ($key,$value)=split(/=/,$item,2);
                   2307:                     $key = &unescape($key);
                   2308:                     next if ($key =~ /^error: 2 /);
                   2309:                     $ruleshash{$key}=&thaw_unescape($value);
                   2310:                 }
                   2311:                 my @esc_order = split(/\&/,$orderitems);
                   2312:                 foreach my $item (@esc_order) {
                   2313:                     push(@ruleorder,&unescape($item));
                   2314:                 }
                   2315:             }
                   2316:         }
                   2317:     }
                   2318:     return (\%ruleshash,\@ruleorder);
                   2319: }
                   2320: 
1.976     raeburn  2321: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2322: 
                   2323: sub get_domain_defaults {
1.1172.2.35  raeburn  2324:     my ($domain,$ignore_cache) = @_;
                   2325:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2326:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2327:     unless ($ignore_cache) {
                   2328:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2329:         if (defined($cached)) {
                   2330:             if (ref($result) eq 'HASH') {
                   2331:                 return %{$result};
                   2332:             }
1.943     raeburn  2333:         }
                   2334:     }
                   2335:     my %domdefaults;
                   2336:     my %domconfig =
1.989     raeburn  2337:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2338:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2339:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2340:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2341:                                   'coursecategories','autoenroll',
                   2342:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2343:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2344:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2345:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2346:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2347:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2348:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2349:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2350:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2351:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2352:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2353:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2354:     } else {
                   2355:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2356:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2357:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2358:     }
1.976     raeburn  2359:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2360:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2361:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2362:         } else {
                   2363:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2364:         }
1.1172.2.6  raeburn  2365:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2366:         foreach my $item (@usertools) {
                   2367:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2368:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2369:             }
                   2370:         }
1.1172.2.29  raeburn  2371:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2372:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2373:         }
1.976     raeburn  2374:     }
1.985     raeburn  2375:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2376:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2377:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2378:         }
                   2379:     }
1.1172.2.9  raeburn  2380:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2381:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2382:     }
1.989     raeburn  2383:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2384:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2385:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2386:         }
                   2387:     }
1.1047    raeburn  2388:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2389:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2390:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2391:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2392:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2393:         }
1.1172.2.41  raeburn  2394:         foreach my $type (@coursetypes) {
                   2395:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2396:                 unless ($type eq 'community') {
                   2397:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2398:                 }
                   2399:             }
                   2400:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2401:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2402:             }
1.1172.2.60  raeburn  2403:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2404:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2405:                     $domdefaults{$type.'postsubtimeout'} =
                   2406:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2407:                 }
                   2408:             }
1.1172.2.30  raeburn  2409:         }
1.1172.2.67  raeburn  2410:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2411:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2412:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2413:                 if (@clonecodes) {
                   2414:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2415:                 }
                   2416:             }
                   2417:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2418:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2419:         }
1.1172.2.103  raeburn  2420:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2421:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2422:         }
1.1047    raeburn  2423:     }
1.1073    raeburn  2424:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2425:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2426:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2427:         }
                   2428:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2429:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2430:         }
1.1172.2.62  raeburn  2431:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2432:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2433:         }
1.1172.2.137  raeburn  2434:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2435:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2436:         }
1.1073    raeburn  2437:     }
1.1172.2.41  raeburn  2438:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2439:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2440:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2441:                             'approval','limit');
                   2442:             foreach my $type (@coursetypes) {
                   2443:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2444:                     my @mgrdc = ();
                   2445:                     foreach my $item (@settings) {
                   2446:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2447:                             push(@mgrdc,$item);
                   2448:                         }
                   2449:                     }
                   2450:                     if (@mgrdc) {
                   2451:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2452:                     }
                   2453:                 }
                   2454:             }
                   2455:         }
                   2456:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2457:             foreach my $type (@coursetypes) {
                   2458:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2459:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2460:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2461:                     }
                   2462:                 }
                   2463:             }
                   2464:         }
                   2465:     }
1.1172.2.46  raeburn  2466:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2467:         $domdefaults{'catauth'} = 'std';
                   2468:         $domdefaults{'catunauth'} = 'std';
                   2469:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2470:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2471:         }
                   2472:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2473:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2474:         }
                   2475:     }
1.1172.2.76  raeburn  2476:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2477:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2478:     }
1.1172.2.89  raeburn  2479:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2480:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2481:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2482:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2483:         }
                   2484:     }
1.1172.2.23  raeburn  2485:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2486:     return %domdefaults;
                   2487: }
                   2488: 
1.1172.2.106  raeburn  2489: sub get_dom_cats {
                   2490:     my ($dom) = @_;
                   2491:     return unless (&domain($dom));
                   2492:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2493:     unless (defined($cached)) {
                   2494:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2495:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2496:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2497:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2498:             } else {
                   2499:                 $cats = {};
                   2500:             }
                   2501:         } else {
                   2502:             $cats = {};
                   2503:         }
                   2504:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2505:     }
                   2506:     return $cats;
                   2507: }
                   2508: 
                   2509: sub get_dom_instcats {
                   2510:     my ($dom) = @_;
                   2511:     return unless (&domain($dom));
                   2512:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2513:     unless (defined($cached)) {
                   2514:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2515:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2516:         if ($totcodes > 0) {
                   2517:             my $caller = 'global';
                   2518:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2519:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2520:                 $instcats = {
                   2521:                                 codes => \%codes,
                   2522:                                 codetitles => \@codetitles,
                   2523:                                 cat_titles => \%cat_titles,
                   2524:                                 cat_order => \%cat_order,
                   2525:                             };
                   2526:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2527:             }
                   2528:         }
                   2529:     }
                   2530:     return $instcats;
                   2531: }
                   2532: 
                   2533: sub retrieve_instcodes {
                   2534:     my ($coursecodes,$dom) = @_;
                   2535:     my $totcodes;
                   2536:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2537:     foreach my $course (keys(%courses)) {
                   2538:         if (ref($courses{$course}) eq 'HASH') {
                   2539:             if ($courses{$course}{'inst_code'} ne '') {
                   2540:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2541:                 $totcodes ++;
                   2542:             }
                   2543:         }
                   2544:     }
                   2545:     return $totcodes;
                   2546: }
                   2547: 
1.1172.2.113  raeburn  2548: # --------------------------------------------- Get domain config for passwords
                   2549: 
                   2550: sub get_passwdconf {
                   2551:     my ($dom) = @_;
                   2552:     my (%passwdconf,$gotconf,$lookup);
                   2553:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2554:     if (defined($cached)) {
                   2555:         if (ref($result) eq 'HASH') {
                   2556:             %passwdconf = %{$result};
                   2557:             $gotconf = 1;
                   2558:         }
                   2559:     }
                   2560:     unless ($gotconf) {
                   2561:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2562:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2563:             %passwdconf = %{$domconfig{'passwords'}};
                   2564:         }
                   2565:         my $cachetime = 24*60*60;
                   2566:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2567:     }
                   2568:     return %passwdconf;
                   2569: }
                   2570: 
1.344     www      2571: # --------------------------------------------------- Assign a key to a student
                   2572: 
                   2573: sub assign_access_key {
1.364     www      2574: #
                   2575: # a valid key looks like uname:udom#comments
                   2576: # comments are being appended
                   2577: #
1.498     www      2578:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2579:     $kdom=
1.620     albertel 2580:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2581:     $knum=
1.620     albertel 2582:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2583:     $cdom=
1.620     albertel 2584:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2585:     $cnum=
1.620     albertel 2586:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2587:     $udom=$env{'user.name'} unless (defined($udom));
                   2588:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2589:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2590:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2591:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2592:                                                   # assigned to this person
                   2593:                                                   # - this should not happen,
1.345     www      2594:                                                   # unless something went wrong
                   2595:                                                   # the first time around
                   2596: # ready to assign
1.364     www      2597:         $logentry=$1.'; '.$logentry;
1.496     www      2598:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2599:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2600: # key now belongs to user
1.346     www      2601: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2602:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2603:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2604:                 return 'ok';
                   2605:             } else {
                   2606:                 return 
                   2607:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2608: 	    }
                   2609:         } else {
                   2610:             return 'error: Could not assign key, try again later.';
                   2611:         }
1.364     www      2612:     } elsif (!$existing{$ckey}) {
1.345     www      2613: # the key does not exist
                   2614: 	return 'error: The key does not exist';
                   2615:     } else {
                   2616: # the key is somebody else's
                   2617: 	return 'error: The key is already in use';
                   2618:     }
1.344     www      2619: }
                   2620: 
1.364     www      2621: # ------------------------------------------ put an additional comment on a key
                   2622: 
                   2623: sub comment_access_key {
                   2624: #
                   2625: # a valid key looks like uname:udom#comments
                   2626: # comments are being appended
                   2627: #
                   2628:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2629:     $cdom=
1.620     albertel 2630:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2631:     $cnum=
1.620     albertel 2632:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2633:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2634:     if ($existing{$ckey}) {
                   2635:         $existing{$ckey}.='; '.$logentry;
                   2636: # ready to assign
1.367     www      2637:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2638:                                                  $cdom,$cnum) eq 'ok') {
                   2639: 	    return 'ok';
                   2640:         } else {
                   2641: 	    return 'error: Count not store comment.';
                   2642:         }
                   2643:     } else {
                   2644: # the key does not exist
                   2645: 	return 'error: The key does not exist';
                   2646:     }
                   2647: }
                   2648: 
1.344     www      2649: # ------------------------------------------------------ Generate a set of keys
                   2650: 
                   2651: sub generate_access_keys {
1.364     www      2652:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2653:     $cdom=
1.620     albertel 2654:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2655:     $cnum=
1.620     albertel 2656:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2657:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2658:     unless (($cdom) && ($cnum)) { return 0; }
                   2659:     if ($number>10000) { return 0; }
                   2660:     sleep(2); # make sure don't get same seed twice
                   2661:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2662:     my $total=0;
                   2663:     for (my $i=1;$i<=$number;$i++) {
                   2664:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2665:                   sprintf("%lx",int(100000*rand)).'-'.
                   2666:                   sprintf("%lx",int(100000*rand));
                   2667:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2668:        $newkey=~s/0/h/g; # and also 0 and O
                   2669:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2670:        if ($existing{$newkey}) {
                   2671:            $i--;
                   2672:        } else {
1.364     www      2673: 	  if (&put('accesskeys',
                   2674:               { $newkey => '# generated '.localtime().
1.620     albertel 2675:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2676:                            '; '.$logentry },
                   2677: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2678:               $total++;
                   2679: 	  }
                   2680:        }
                   2681:     }
1.620     albertel 2682:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2683:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2684:     return $total;
                   2685: }
                   2686: 
                   2687: # ------------------------------------------------------- Validate an accesskey
                   2688: 
                   2689: sub validate_access_key {
                   2690:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2691:     $cdom=
1.620     albertel 2692:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2693:     $cnum=
1.620     albertel 2694:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2695:     $udom=$env{'user.domain'} unless (defined($udom));
                   2696:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2697:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2698:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2699: }
                   2700: 
                   2701: # ------------------------------------- Find the section of student in a course
1.652     albertel 2702: sub devalidate_getsection_cache {
                   2703:     my ($udom,$unam,$courseid)=@_;
                   2704:     my $hashid="$udom:$unam:$courseid";
                   2705:     &devalidate_cache_new('getsection',$hashid);
                   2706: }
1.298     matthew  2707: 
1.815     albertel 2708: sub courseid_to_courseurl {
                   2709:     my ($courseid) = @_;
                   2710:     #already url style courseid
                   2711:     return $courseid if ($courseid =~ m{^/});
                   2712: 
                   2713:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2714: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2715: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2716: 	return "/$cdom/$cnum";
                   2717:     }
                   2718: 
                   2719:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2720:     if (exists($courseinfo{'num'})) {
                   2721: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2722:     }
                   2723: 
                   2724:     return undef;
                   2725: }
                   2726: 
1.298     matthew  2727: sub getsection {
                   2728:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2729:     my $cachetime=1800;
1.551     albertel 2730: 
                   2731:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2732:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2733:     if (defined($cached)) { return $result; }
                   2734: 
1.298     matthew  2735:     my %Pending; 
                   2736:     my %Expired;
                   2737:     #
                   2738:     # Each role can either have not started yet (pending), be active, 
                   2739:     #    or have expired.
                   2740:     #
                   2741:     # If there is an active role, we are done.
                   2742:     #
                   2743:     # If there is more than one role which has not started yet, 
                   2744:     #     choose the one which will start sooner
                   2745:     # If there is one role which has not started yet, return it.
                   2746:     #
                   2747:     # If there is more than one expired role, choose the one which ended last.
                   2748:     # If there is a role which has expired, return it.
                   2749:     #
1.815     albertel 2750:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2751:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2752:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2753:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2754:         my $section=$1;
                   2755:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2756:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2757:         my $now=time;
1.548     albertel 2758:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2759:             $Expired{$end}=$section;
                   2760:             next;
                   2761:         }
1.548     albertel 2762:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2763:             $Pending{$start}=$section;
                   2764:             next;
                   2765:         }
1.599     albertel 2766:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2767:     }
                   2768:     #
                   2769:     # Presumedly there will be few matching roles from the above
                   2770:     # loop and the sorting time will be negligible.
                   2771:     if (scalar(keys(%Pending))) {
                   2772:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2773:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2774:     } 
                   2775:     if (scalar(keys(%Expired))) {
                   2776:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2777:         my $time = pop(@sorted);
1.599     albertel 2778:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2779:     }
1.599     albertel 2780:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2781: }
1.70      www      2782: 
1.599     albertel 2783: sub save_cache {
                   2784:     &purge_remembered();
1.722     albertel 2785:     #&Apache::loncommon::validate_page();
1.620     albertel 2786:     undef(%env);
1.780     albertel 2787:     undef($env_loaded);
1.599     albertel 2788: }
1.452     albertel 2789: 
1.599     albertel 2790: my $to_remember=-1;
                   2791: my %remembered;
                   2792: my %accessed;
                   2793: my $kicks=0;
                   2794: my $hits=0;
1.849     albertel 2795: sub make_key {
                   2796:     my ($name,$id) = @_;
1.872     albertel 2797:     if (length($id) > 65 
                   2798: 	&& length(&escape($id)) > 200) {
                   2799: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2800:     }
1.849     albertel 2801:     return &escape($name.':'.$id);
                   2802: }
                   2803: 
1.599     albertel 2804: sub devalidate_cache_new {
                   2805:     my ($name,$id,$debug) = @_;
                   2806:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2807:     my $remembered_id=$name.':'.$id;
1.849     albertel 2808:     $id=&make_key($name,$id);
1.599     albertel 2809:     $memcache->delete($id);
1.1172.2.81  raeburn  2810:     delete($remembered{$remembered_id});
                   2811:     delete($accessed{$remembered_id});
1.599     albertel 2812: }
                   2813: 
                   2814: sub is_cached_new {
                   2815:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2816:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2817:                                      # keys in %remembered hash, which persists for
                   2818:                                      # duration of request (no restriction on key length).
                   2819:     if (exists($remembered{$remembered_id})) {
                   2820: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2821: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2822: 	$hits++;
1.1172.2.81  raeburn  2823: 	return ($remembered{$remembered_id},1);
1.599     albertel 2824:     }
1.1172.2.81  raeburn  2825:     $id=&make_key($name,$id);
1.599     albertel 2826:     my $value = $memcache->get($id);
                   2827:     if (!(defined($value))) {
                   2828: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2829: 	return (undef,undef);
1.416     albertel 2830:     }
1.599     albertel 2831:     if ($value eq '__undef__') {
                   2832: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2833: 	$value=undef;
                   2834:     }
1.1172.2.81  raeburn  2835:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2836:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2837:     return ($value,1);
                   2838: }
                   2839: 
                   2840: sub do_cache_new {
                   2841:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2842:     my $remembered_id=$name.':'.$id;
1.849     albertel 2843:     $id=&make_key($name,$id);
1.599     albertel 2844:     my $setvalue=$value;
                   2845:     if (!defined($setvalue)) {
                   2846: 	$setvalue='__undef__';
                   2847:     }
1.623     albertel 2848:     if (!defined($time) ) {
                   2849: 	$time=600;
                   2850:     }
1.599     albertel 2851:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2852:     my $result = $memcache->set($id,$setvalue,$time);
                   2853:     if (! $result) {
1.872     albertel 2854: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2855: 	$memcache->disconnect_all();
1.872     albertel 2856:     }
1.600     albertel 2857:     # need to make a copy of $value
1.1172.2.81  raeburn  2858:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2859:     return $value;
                   2860: }
                   2861: 
                   2862: sub make_room {
1.1172.2.81  raeburn  2863:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2864: 
1.1172.2.81  raeburn  2865:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2866:                                     : $value;
1.599     albertel 2867:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2868:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2869:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2870:     my $to_kick;
                   2871:     my $max_time=0;
                   2872:     foreach my $other (keys(%accessed)) {
                   2873: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2874: 	    $to_kick=$other;
                   2875: 	    $max_time=&tv_interval($accessed{$other});
                   2876: 	}
                   2877:     }
                   2878:     delete($remembered{$to_kick});
                   2879:     delete($accessed{$to_kick});
                   2880:     $kicks++;
                   2881:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2882:     return;
                   2883: }
                   2884: 
1.599     albertel 2885: sub purge_remembered {
1.604     albertel 2886:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2887:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2888:     undef(%remembered);
                   2889:     undef(%accessed);
1.428     albertel 2890: }
1.70      www      2891: # ------------------------------------- Read an entry from a user's environment
                   2892: 
                   2893: sub userenvironment {
                   2894:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2895:     my $items;
                   2896:     foreach my $item (@what) {
                   2897:         $items.=&escape($item).'&';
                   2898:     }
                   2899:     $items=~s/\&$//;
1.70      www      2900:     my %returnhash=();
1.1009    raeburn  2901:     my $uhome = &homeserver($unam,$udom);
                   2902:     unless ($uhome eq 'no_host') {
                   2903:         my @answer=split(/\&/, 
                   2904:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2905:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2906:             return %returnhash;
                   2907:         }
1.1009    raeburn  2908:         my $i;
                   2909:         for ($i=0;$i<=$#what;$i++) {
                   2910: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2911:         }
1.70      www      2912:     }
                   2913:     return %returnhash;
1.1       albertel 2914: }
                   2915: 
1.617     albertel 2916: # ---------------------------------------------------------- Get a studentphoto
                   2917: sub studentphoto {
                   2918:     my ($udom,$unam,$ext) = @_;
                   2919:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2920:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2921:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2922:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2923:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2924:             } else {
                   2925:                 my ($result,$perm_reqd)=
1.707     albertel 2926: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2927:                 if ($result eq 'ok') {
                   2928:                     if (!($perm_reqd eq 'yes')) {
                   2929:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2930:                     }
                   2931:                 }
                   2932:             }
                   2933:         }
                   2934:     } else {
                   2935:         my ($result,$perm_reqd) = 
1.707     albertel 2936: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2937:         if ($result eq 'ok') {
                   2938:             if (!($perm_reqd eq 'yes')) {
                   2939:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2940:             }
                   2941:         }
                   2942:     }
                   2943:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2944: }
                   2945: 
                   2946: sub retrievestudentphoto {
                   2947:     my ($udom,$unam,$ext,$type) = @_;
                   2948:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2949:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2950:     if ($ret eq 'ok') {
                   2951:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2952:         if ($type eq 'thumbnail') {
                   2953:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2954:         }
                   2955:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2956:         return $tokenurl;
                   2957:     } else {
                   2958:         if ($type eq 'thumbnail') {
                   2959:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2960:         } else { 
                   2961:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2962:         }
1.617     albertel 2963:     }
                   2964: }
                   2965: 
1.263     www      2966: # -------------------------------------------------------------------- New chat
                   2967: 
                   2968: sub chatsend {
1.724     raeburn  2969:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2970:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2971:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2972:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2973:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2974: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2975: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2976: }
                   2977: 
                   2978: # ------------------------------------------ Find current version of a resource
                   2979: 
                   2980: sub getversion {
                   2981:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2982:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2983:     return &currentversion(&filelocation('',$fname));
                   2984: }
                   2985: 
                   2986: sub currentversion {
                   2987:     my $fname=shift;
                   2988:     my $author=$fname;
                   2989:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2990:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2991:     my $home=&homeserver($uname,$udom);
1.292     www      2992:     if ($home eq 'no_host') { 
                   2993:         return -1; 
                   2994:     }
1.1112    www      2995:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2996:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2997: 	return -1;
                   2998:     }
1.1112    www      2999:     return $answer;
1.263     www      3000: }
                   3001: 
1.1111    www      3002: #
                   3003: # Return special version number of resource if set by override, empty otherwise
                   3004: #
                   3005: sub usedversion {
                   3006:     my $fname=shift;
                   3007:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3008:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3009:     if ($urlversion) { return $urlversion; }
                   3010:     return '';
                   3011: }
                   3012: 
1.1       albertel 3013: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3014: 
1.1       albertel 3015: sub subscribe {
                   3016:     my $fname=shift;
1.761     raeburn  3017:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3018:     $fname=~s/[\n\r]//g;
1.1       albertel 3019:     my $author=$fname;
                   3020:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3021:     my ($udom,$uname)=split(/\//,$author);
                   3022:     my $home=homeserver($uname,$udom);
1.335     albertel 3023:     if ($home eq 'no_host') {
                   3024:         return 'not_found';
1.1       albertel 3025:     }
                   3026:     my $answer=reply("sub:$fname",$home);
1.64      www      3027:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3028: 	$answer.=' by '.$home;
                   3029:     }
1.1       albertel 3030:     return $answer;
                   3031: }
                   3032:     
1.8       www      3033: # -------------------------------------------------------------- Replicate file
                   3034: 
                   3035: sub repcopy {
                   3036:     my $filename=shift;
1.23      www      3037:     $filename=~s/\/+/\//g;
1.1142    raeburn  3038:     my $londocroot = $perlvar{'lonDocRoot'};
                   3039:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3040:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3041:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3042: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3043: 	return &repcopy_userfile($filename);
                   3044:     }
1.532     albertel 3045:     $filename=~s/[\n\r]//g;
1.8       www      3046:     my $transname="$filename.in.transfer";
1.828     www      3047: # FIXME: this should flock
1.607     raeburn  3048:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3049:     my $remoteurl=subscribe($filename);
1.64      www      3050:     if ($remoteurl =~ /^con_lost by/) {
                   3051: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3052:            return 'unavailable';
1.8       www      3053:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3054: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3055: 	   return 'not_found';
1.64      www      3056:     } elsif ($remoteurl =~ /^rejected by/) {
                   3057: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3058:            return 'forbidden';
1.20      www      3059:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3060:            return 'ok';
1.8       www      3061:     } else {
1.290     www      3062:         my $author=$filename;
                   3063:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3064:         my ($udom,$uname)=split(/\//,$author);
                   3065:         my $home=homeserver($uname,$udom);
                   3066:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3067:            my @parts=split(/\//,$filename);
                   3068:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3069:            if ($path ne "$londocroot/res") {
1.8       www      3070:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3071: 	       return 'bad_request';
1.8       www      3072:            }
                   3073:            my $count;
                   3074:            for ($count=5;$count<$#parts;$count++) {
                   3075:                $path.="/$parts[$count]";
                   3076:                if ((-e $path)!=1) {
                   3077: 		   mkdir($path,0777);
                   3078:                }
                   3079:            }
                   3080:            my $ua=new LWP::UserAgent;
                   3081:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3082:            my $response=$ua->request($request,$transname);
                   3083:            if ($response->is_error()) {
                   3084: 	       unlink($transname);
                   3085:                my $message=$response->status_line;
1.672     albertel 3086:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3087:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3088:                return 'unavailable';
1.8       www      3089:            } else {
1.16      www      3090: 	       if ($remoteurl!~/\.meta$/) {
                   3091:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3092:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3093:                   if ($mresponse->is_error()) {
                   3094: 		      unlink($filename.'.meta');
                   3095:                       &logthis(
1.672     albertel 3096:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3097:                   }
                   3098: 	       }
1.8       www      3099:                rename($transname,$filename);
1.607     raeburn  3100:                return 'ok';
1.8       www      3101:            }
1.290     www      3102:        }
1.8       www      3103:     }
1.330     www      3104: }
                   3105: 
1.1172.2.124  raeburn  3106: # ------------------------------------------------- Unsubscribe from a resource
                   3107: 
                   3108: sub unsubscribe {
                   3109:     my ($fname) = @_;
                   3110:     my $answer;
                   3111:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3112:     $fname=~s/[\n\r]//g;
                   3113:     my $author=$fname;
                   3114:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3115:     my ($udom,$uname)=split(/\//,$author);
                   3116:     my $home=homeserver($uname,$udom);
                   3117:     if ($home eq 'no_host') {
                   3118:         $answer = 'no_host';
                   3119:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3120:         $answer = 'home';
                   3121:     } else {
1.1172.2.125  raeburn  3122:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3123:     }
                   3124:     return $answer;
                   3125: }
                   3126: 
1.330     www      3127: # ------------------------------------------------ Get server side include body
                   3128: sub ssi_body {
1.381     albertel 3129:     my ($filelink,%form)=@_;
1.606     matthew  3130:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3131:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3132:     }
1.953     www      3133:     my $output='';
                   3134:     my $response;
1.980     raeburn  3135:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3136:        ($output,$response)=&externalssi($filelink);
1.953     www      3137:     } else {
1.1004    droeschl 3138:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3139:        $filelink .= 'inhibitmenu=yes';
1.953     www      3140:        ($output,$response)=&ssi($filelink,%form);
                   3141:     }
1.778     albertel 3142:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3143:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3144:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3145:     if (wantarray) {
                   3146:         return ($output, $response);
                   3147:     } else {
                   3148:         return $output;
                   3149:     }
1.8       www      3150: }
                   3151: 
1.15      www      3152: # --------------------------------------------------------- Server Side Include
                   3153: 
1.782     albertel 3154: sub absolute_url {
                   3155:     my ($host_name) = @_;
                   3156:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3157:     if ($host_name eq '') {
                   3158: 	$host_name = $ENV{'SERVER_NAME'};
                   3159:     }
                   3160:     return $protocol.$host_name;
                   3161: }
                   3162: 
1.942     foxr     3163: #
                   3164: #   Server side include.
                   3165: # Parameters:
                   3166: #  fn     Possibly encrypted resource name/id.
                   3167: #  form   Hash that describes how the rendering should be done
                   3168: #         and other things.
1.944     foxr     3169: # Returns:
1.950     raeburn  3170: #   Scalar context: The content of the response.
                   3171: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3172: #     
1.15      www      3173: sub ssi {
                   3174: 
1.944     foxr     3175:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3176:     my ($request,$response);
1.711     albertel 3177: 
                   3178:     $form{'no_update_last_known'}=1;
1.895     albertel 3179:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3180:     if (%form) {
1.782     albertel 3181:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3182:       $request->content(join('&',map {
                   3183:             my $name = escape($_);
                   3184:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3185:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3186:             : &escape($form{$_}) );
                   3187:         } keys(%form)));
1.23      www      3188:     } else {
1.782     albertel 3189:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3190:     }
                   3191: 
1.15      www      3192:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3193: 
1.1172.2.101  raeburn  3194:     if (($env{'request.course.id'}) &&
                   3195:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3196:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3197:         ($form{'grade_symb'} ne '') &&
                   3198:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3199:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3200:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3201:             my $ua=new LWP::UserAgent;
                   3202:             $ua->local_address('127.0.0.1');
                   3203:             $response = $ua->request($request);
                   3204:         } else {
                   3205:             {
                   3206:                 require LWP::Protocol::http;
                   3207:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3208:                 my $ua=new LWP::UserAgent;
                   3209:                 $response = $ua->request($request);
                   3210:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3211:             }
                   3212:         }
                   3213:     } else {
                   3214:         my $ua=new LWP::UserAgent;
                   3215:         $response = $ua->request($request);
                   3216:     }
1.944     foxr     3217:     if (wantarray) {
1.1172.2.3  raeburn  3218: 	return ($response->content, $response);
1.944     foxr     3219:     } else {
1.1172.2.3  raeburn  3220: 	return $response->content;
1.942     foxr     3221:     }
1.324     www      3222: }
                   3223: 
                   3224: sub externalssi {
                   3225:     my ($url)=@_;
                   3226:     my $ua=new LWP::UserAgent;
                   3227:     my $request=new HTTP::Request('GET',$url);
                   3228:     my $response=$ua->request($request);
1.954     raeburn  3229:     if (wantarray) {
                   3230:         return ($response->content, $response);
                   3231:     } else {
                   3232:         return $response->content;
                   3233:     }
1.15      www      3234: }
1.254     www      3235: 
1.1172.2.98  raeburn  3236: # If the local copy of a replicated resource is outdated, trigger a
                   3237: # connection from the homeserver to flush the delayed queue. If no update
                   3238: # happens, remove local copies of outdated resource (and corresponding
                   3239: # metadata file).
                   3240: 
                   3241: sub remove_stale_resfile {
                   3242:     my ($url) = @_;
                   3243:     my $removed;
                   3244:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3245:         my $audom = $1;
                   3246:         my $auname = $2;
                   3247:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3248:             my $homeserver = &homeserver($auname,$audom);
                   3249:             unless (($homeserver eq 'no_host') ||
                   3250:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3251:                 my $fname = &filelocation('',$url);
                   3252:                 if (-e $fname) {
                   3253:                     my $hostname = &hostname($homeserver);
                   3254:                     if ($hostname) {
1.1172.2.120  raeburn  3255:                         my $protocol = $protocol{$homeserver};
                   3256:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3257:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3258:                         my $ua=new LWP::UserAgent;
                   3259:                         $ua->timeout(5);
1.1172.2.98  raeburn  3260:                         my $request=new HTTP::Request('HEAD',$uri);
                   3261:                         my $response=$ua->request($request);
                   3262:                         if ($response->is_success()) {
                   3263:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3264:                             my $locmodtime = (stat($fname))[9];
                   3265:                             if ($locmodtime < $remmodtime) {
                   3266:                                 my $stale;
                   3267:                                 my $answer = &reply('pong',$homeserver);
                   3268:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3269:                                     sleep(0.2);
                   3270:                                     $locmodtime = (stat($fname))[9];
                   3271:                                     if ($locmodtime < $remmodtime) {
                   3272:                                         my $posstransfer = $fname.'.in.transfer';
                   3273:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3274:                                             $removed = 1;
                   3275:                                         } else {
                   3276:                                             $stale = 1;
                   3277:                                         }
                   3278:                                     } else {
                   3279:                                         $removed = 1;
                   3280:                                     }
                   3281:                                 } else {
                   3282:                                     $stale = 1;
                   3283:                                 }
                   3284:                                 if ($stale) {
1.1172.2.124  raeburn  3285:                                     if (unlink($fname)) {
                   3286:                                         if ($uri!~/\.meta$/) {
                   3287:                                             if (-e $fname.'.meta') {
                   3288:                                                 unlink($fname.'.meta');
                   3289:                                             }
                   3290:                                         }
                   3291:                                         my $unsubresult = &unsubscribe($fname);
                   3292:                                         unless ($unsubresult eq 'ok') {
                   3293:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3294:                                         }
                   3295:                                         $removed = 1;
1.1172.2.98  raeburn  3296:                                     }
                   3297:                                 }
                   3298:                             }
                   3299:                         }
                   3300:                     }
                   3301:                 }
                   3302:             }
                   3303:         }
                   3304:     }
                   3305:     return $removed;
                   3306: }
                   3307: 
1.492     albertel 3308: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3309: 
                   3310: sub allowuploaded {
                   3311:     my ($srcurl,$url)=@_;
                   3312:     $url=&clutter(&declutter($url));
                   3313:     my $dir=$url;
                   3314:     $dir=~s/\/[^\/]+$//;
                   3315:     my %httpref=();
                   3316:     my $httpurl=&hreflocation('',$url);
                   3317:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3318:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3319: }
1.477     raeburn  3320: 
1.1172.2.13  raeburn  3321: #
                   3322: # Determine if the current user should be able to edit a particular resource,
                   3323: # when viewing in course context.
                   3324: # (a) When viewing resource used to determine if "Edit" item is included in
                   3325: #     Functions.
                   3326: # (b) When displaying folder contents in course editor, used to determine if
                   3327: #     "Edit" link will be displayed alongside resource.
                   3328: #
                   3329: #  input: six args -- filename (decluttered), course number, course domain,
                   3330: #                   url, symb (if registered) and group (if this is a group
                   3331: #                   item -- e.g., bulletin board, group page etc.).
                   3332: #  output: array of five scalars --
                   3333: #          $cfile -- url for file editing if editable on current server
                   3334: #          $home -- homeserver of resource (i.e., for author if published,
                   3335: #                                           or course if uploaded.).
                   3336: #          $switchserver --  1 if server switch will be needed.
                   3337: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3338: #          $forceview -- 1 if icon/link should be to go to view mode
                   3339: #
                   3340: 
                   3341: sub can_edit_resource {
                   3342:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3343:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3344: #
                   3345: # For aboutme pages user can only edit his/her own.
                   3346: #
                   3347:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3348:         my ($sdom,$sname) = ($1,$2);
                   3349:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3350:             $home = $env{'user.home'};
                   3351:             $cfile = $resurl;
                   3352:             if ($env{'form.forceedit'}) {
                   3353:                 $forceview = 1;
                   3354:             } else {
                   3355:                 $forceedit = 1;
                   3356:             }
                   3357:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3358:         } else {
                   3359:             return;
                   3360:         }
                   3361:     }
                   3362: 
                   3363:     if ($env{'request.course.id'}) {
                   3364:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3365:         if ($group ne '') {
                   3366: # if this is a group homepage or group bulletin board, check group privs
                   3367:             my $allowed = 0;
                   3368:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3369:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3370:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3371:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3372:                     $allowed = 1;
                   3373:                 }
                   3374:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3375:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3376:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3377:                     $allowed = 1;
                   3378:                 }
                   3379:             }
                   3380:             if ($allowed) {
                   3381:                 $home=&homeserver($cnum,$cdom);
                   3382:                 if ($env{'form.forceedit'}) {
                   3383:                     $forceview = 1;
                   3384:                 } else {
                   3385:                     $forceedit = 1;
                   3386:                 }
                   3387:                 $cfile = $resurl;
                   3388:             } else {
                   3389:                 return;
                   3390:             }
                   3391:         } else {
1.1172.2.15  raeburn  3392:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3393:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3394:                     return;
                   3395:                 }
                   3396:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3397: #
                   3398: # No edit allowed where CC has switched to student role.
                   3399: #
                   3400:                 return;
                   3401:             }
                   3402:         }
                   3403:     }
                   3404: 
                   3405:     if ($file ne '') {
                   3406:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3407:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3408:                 $uploaded = 1;
                   3409:                 $incourse = 1;
                   3410:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3411:                     $cfile = &hreflocation('',$file);
                   3412:                     if ($env{'form.forceedit'}) {
                   3413:                         $forceview = 1;
                   3414:                     } else {
                   3415:                         $forceedit = 1;
                   3416:                     }
                   3417:                 }
                   3418:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3419:                 $incourse = 1;
                   3420:                 if ($env{'form.forceedit'}) {
                   3421:                     $forceview = 1;
                   3422:                 } else {
                   3423:                     $forceedit = 1;
                   3424:                 }
                   3425:                 $cfile = $resurl;
                   3426:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3427:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3428:                     $incourse = 1;
                   3429:                     if ($env{'form.forceedit'}) {
                   3430:                         $forceview = 1;
                   3431:                     } else {
                   3432:                         $forceedit = 1;
                   3433:                     }
                   3434:                     $cfile = $resurl;
                   3435:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3436:                     $incourse = 1;
                   3437:                     $cfile = $resurl.'/smpedit';
                   3438:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3439:                     $incourse = 1;
                   3440:                     if ($env{'form.forceedit'}) {
                   3441:                         $forceview = 1;
                   3442:                     } else {
                   3443:                         $forceedit = 1;
                   3444:                     }
                   3445:                     $cfile = $resurl;
1.1172.2.122  raeburn  3446:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3447:                     my ($map,$id,$res) = &decode_symb($symb);
                   3448:                     if ($map =~ /\.page$/) {
                   3449:                         $incourse = 1;
                   3450:                         if ($env{'form.forceedit'}) {
                   3451:                             $forceview = 1;
                   3452:                             $cfile = $map;
                   3453:                         } else {
                   3454:                             $forceedit = 1;
                   3455:                             $cfile =  '/adm/wrapper'.$resurl;
                   3456:                         }
                   3457:                     }
1.1172.2.15  raeburn  3458:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3459:                     $incourse = 1;
                   3460:                     if ($env{'form.forceedit'}) {
                   3461:                         $forceview = 1;
                   3462:                     } else {
                   3463:                         $forceedit = 1;
                   3464:                     }
                   3465:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3466:                 }
                   3467:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3468:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3469:                 if (&is_on_map($template)) {
                   3470:                     $incourse = 1;
                   3471:                     $forceview = 1;
                   3472:                     $cfile = $template;
                   3473:                 }
                   3474:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3475:                 $incourse = 1;
                   3476:                 if ($env{'form.forceedit'}) {
                   3477:                     $forceview = 1;
                   3478:                 } else {
                   3479:                     $forceedit = 1;
                   3480:                 }
                   3481:                 $cfile = $resurl;
1.1172.2.13  raeburn  3482:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3483:                 $incourse = 1;
                   3484:                 $forceview = 1;
                   3485:                 if ($symb) {
                   3486:                     my ($map,$id,$res)=&decode_symb($symb);
                   3487:                     $env{'request.symb'} = $symb;
                   3488:                     $cfile = &clutter($res);
                   3489:                 } else {
                   3490:                     $cfile = $env{'form.suppurl'};
                   3491:                     $cfile =~ s{^http://}{};
                   3492:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3493:                 }
1.1172.2.31  raeburn  3494:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3495:                 if ($env{'form.forceedit'}) {
                   3496:                     $forceview = 1;
                   3497:                 } else {
                   3498:                     $forceedit = 1;
                   3499:                 }
                   3500:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3501:             }
                   3502:         }
                   3503:         if ($uploaded || $incourse) {
                   3504:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3505:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3506:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3507:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3508:             # Check that the user has permission to edit this resource
                   3509:             my $setpriv = 1;
                   3510:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3511:             if (defined($cfudom)) {
                   3512:                 $home=&homeserver($cfuname,$cfudom);
                   3513:                 $cfile=$file;
                   3514:             }
                   3515:         }
                   3516:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3517:             (($home ne '') && ($home ne 'no_host'))) {
                   3518:             my @ids=&current_machine_ids();
                   3519:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3520:                 $switchserver=1;
                   3521:             }
                   3522:         }
                   3523:     }
                   3524:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3525: }
                   3526: 
                   3527: sub is_course_upload {
                   3528:     my ($file,$cnum,$cdom) = @_;
                   3529:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3530:     $uploadpath =~ s{^\/}{};
                   3531:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3532:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3533:         return 1;
                   3534:     }
                   3535:     return;
                   3536: }
                   3537: 
                   3538: sub in_course {
                   3539:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3540:     if ($hideprivileged) {
                   3541:         my $skipuser;
1.1172.2.23  raeburn  3542:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3543:         my @possdoms = ($cdom);
                   3544:         if ($coursehash{'checkforpriv'}) {
                   3545:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3546:         }
                   3547:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3548:             $skipuser = 1;
                   3549:             if ($coursehash{'nothideprivileged'}) {
                   3550:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3551:                     my $user;
                   3552:                     if ($item =~ /:/) {
                   3553:                         $user = $item;
                   3554:                     } else {
                   3555:                         $user = join(':',split(/[\@]/,$item));
                   3556:                     }
                   3557:                     if ($user eq $uname.':'.$udom) {
                   3558:                         undef($skipuser);
                   3559:                         last;
                   3560:                     }
                   3561:                 }
                   3562:             }
                   3563:             if ($skipuser) {
                   3564:                 return 0;
                   3565:             }
                   3566:         }
                   3567:     }
                   3568:     $type ||= 'any';
                   3569:     if (!defined($cdom) || !defined($cnum)) {
                   3570:         my $cid  = $env{'request.course.id'};
                   3571:         $cdom = $env{'course.'.$cid.'.domain'};
                   3572:         $cnum = $env{'course.'.$cid.'.num'};
                   3573:     }
                   3574:     my $typesref;
                   3575:     if (($type eq 'any') || ($type eq 'all')) {
                   3576:         $typesref = ['active','previous','future'];
                   3577:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3578:         $typesref = [$type];
                   3579:     }
                   3580:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3581:                               $typesref,undef,[$cdom]);
                   3582:     my ($tmp) = keys(%roles);
                   3583:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3584:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3585:     if (@course_roles > 0) {
                   3586:         return 1;
                   3587:     }
                   3588:     return 0;
                   3589: }
                   3590: 
1.478     albertel 3591: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3592: # input: action, courseID, current domain, intended
1.637     raeburn  3593: #        path to file, source of file, instruction to parse file for objects,
                   3594: #        ref to hash for embedded objects,
                   3595: #        ref to hash for codebase of java objects.
1.1095    raeburn  3596: #        reference to scalar to accommodate mime type determined
                   3597: #          from File::MMagic if $parser = parse.
1.637     raeburn  3598: #
1.485     raeburn  3599: # output: url to file (if action was uploaddoc), 
                   3600: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3601: #
1.478     albertel 3602: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3603: # course.
1.477     raeburn  3604: #
1.478     albertel 3605: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3606: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3607: #          course's home server.
1.477     raeburn  3608: #
1.478     albertel 3609: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3610: #          be copied from $source (current location) to 
                   3611: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3612: #         and will then be copied to
                   3613: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3614: #         course's home server.
1.485     raeburn  3615: #
1.481     raeburn  3616: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3617: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3618: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3619: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3620: #         in course's home server.
1.637     raeburn  3621: #
1.477     raeburn  3622: 
                   3623: sub process_coursefile {
1.1095    raeburn  3624:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3625:         $mimetype)=@_;
1.477     raeburn  3626:     my $fetchresult;
1.638     albertel 3627:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3628:     if ($action eq 'propagate') {
1.638     albertel 3629:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3630: 			     $home);
1.481     raeburn  3631:     } else {
1.477     raeburn  3632:         my $fpath = '';
                   3633:         my $fname = $file;
1.478     albertel 3634:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3635:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3636:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3637:         if ($action eq 'copy') {
                   3638:             if ($source eq '') {
                   3639:                 $fetchresult = 'no source file';
                   3640:                 return $fetchresult;
                   3641:             } else {
                   3642:                 my $destination = $filepath.'/'.$fname;
                   3643:                 rename($source,$destination);
                   3644:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3645:                                  $home);
1.481     raeburn  3646:             }
                   3647:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3648:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3649:             print $fh $env{'form.'.$source};
1.481     raeburn  3650:             close($fh);
1.637     raeburn  3651:             if ($parser eq 'parse') {
1.1024    raeburn  3652:                 my $mm = new File::MMagic;
1.1095    raeburn  3653:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3654:                 if ($type eq 'text/html') {
1.1024    raeburn  3655:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3656:                     unless ($parse_result eq 'ok') {
                   3657:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3658:                     }
1.637     raeburn  3659:                 }
1.1095    raeburn  3660:                 if (ref($mimetype)) {
                   3661:                     $$mimetype = $type;
                   3662:                 } 
1.637     raeburn  3663:             }
1.477     raeburn  3664:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3665:                                  $home);
1.481     raeburn  3666:             if ($fetchresult eq 'ok') {
                   3667:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3668:             } else {
                   3669:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3670:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3671:                 return '/adm/notfound.html';
                   3672:             }
1.477     raeburn  3673:         }
                   3674:     }
1.485     raeburn  3675:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3676:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3677:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3678:     }
                   3679:     return $fetchresult;
                   3680: }
                   3681: 
1.637     raeburn  3682: sub build_filepath {
                   3683:     my ($fpath) = @_;
                   3684:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3685:     unless ($fpath eq '') {
                   3686:         my @parts=split('/',$fpath);
                   3687:         foreach my $part (@parts) {
                   3688:             $filepath.= '/'.$part;
                   3689:             if ((-e $filepath)!=1) {
                   3690:                 mkdir($filepath,0777);
                   3691:             }
                   3692:         }
                   3693:     }
                   3694:     return $filepath;
                   3695: }
                   3696: 
                   3697: sub store_edited_file {
1.638     albertel 3698:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3699:     my $file = $primary_url;
                   3700:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3701:     my $fpath = '';
                   3702:     my $fname = $file;
                   3703:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3704:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3705:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3706:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3707:     print $fh $content;
                   3708:     close($fh);
1.638     albertel 3709:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3710:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3711: 			  $home);
1.637     raeburn  3712:     if ($$fetchresult eq 'ok') {
                   3713:         return '/uploaded/'.$fpath.'/'.$fname;
                   3714:     } else {
1.638     albertel 3715:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3716: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3717:         return '/adm/notfound.html';
                   3718:     }
                   3719: }
                   3720: 
1.531     albertel 3721: sub clean_filename {
1.831     albertel 3722:     my ($fname,$args)=@_;
1.315     www      3723: # Replace Windows backslashes by forward slashes
1.257     www      3724:     $fname=~s/\\/\//g;
1.831     albertel 3725:     if (!$args->{'keep_path'}) {
                   3726:         # Get rid of everything but the actual filename
                   3727: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3728:     }
1.315     www      3729: # Replace spaces by underscores
                   3730:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3731: # Transliterate non-ascii text to ascii
                   3732:     my $lang = &Apache::lonlocal::current_language();
                   3733:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3734: # Replace all other weird characters by nothing
1.831     albertel 3735:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3736: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3737: # numbers
                   3738:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3739:     return $fname;
                   3740: }
1.1172.2.110  raeburn  3741: 
1.1051    raeburn  3742: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3743: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3744: # image with the same aspect ratio as the original, but with dimensions which do 
                   3745: # not exceed $resizewidth and $resizeheight.
                   3746:  
1.984     neumanie 3747: sub resizeImage {
1.1051    raeburn  3748:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3749:     my $ima = Image::Magick->new;
                   3750:     my $resized;
                   3751:     if (-e $img_path) {
                   3752:         $ima->Read($img_path);
                   3753:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3754:             my $width = $ima->Get('width');
                   3755:             my $height = $ima->Get('height');
                   3756:             if ($width > $resizewidth) {
                   3757: 	        my $factor = $width/$resizewidth;
                   3758:                 my $newheight = $height/$factor;
                   3759:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3760:                 $resized = 1;
                   3761:             }
                   3762:         }
                   3763:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3764:             my $width = $ima->Get('width');
                   3765:             my $height = $ima->Get('height');
                   3766:             if ($height > $resizeheight) {
                   3767:                 my $factor = $height/$resizeheight;
                   3768:                 my $newwidth = $width/$factor;
                   3769:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3770:                 $resized = 1;
                   3771:             }
                   3772:         }
                   3773:         if ($resized) {
                   3774:             $ima->Write($img_path);
                   3775:         }
                   3776:     }
                   3777:     return;
1.977     amueller 3778: }
                   3779: 
1.608     albertel 3780: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3781: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3782: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3783: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3784: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3785: #                   if 'coursedoc': upload to the current course
                   3786: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3787: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3788: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3789: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3790: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3791: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3792: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3793: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3794: #        $allfiles - reference to hash for embedded objects
                   3795: #        $codebase - reference to hash for codebase of java objects
                   3796: #        $desuname - username for permanent storage of uploaded file
                   3797: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3798: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3799: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3800: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3801: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3802: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3803: #                    from File::MMagic.
1.858     raeburn  3804: # 
1.686     albertel 3805: # output: url of file in userspace, or error: <message> 
                   3806: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3807: 
1.531     albertel 3808: sub userfileupload {
1.1090    raeburn  3809:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3810:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3811:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3812:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3813:     $fname=&clean_filename($fname);
1.1090    raeburn  3814:     # See if there is anything left
1.257     www      3815:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3816:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3817:     if ($fname =~ /^\./) {
                   3818:         my ($s,$usec) = &gettimeofday();
                   3819:         while (length($usec) < 6) {
                   3820:             $usec = '0'.$usec;
                   3821:         }
                   3822:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3823:     }
1.1090    raeburn  3824:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3825:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3826:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3827:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3828:         my $now = time;
1.1090    raeburn  3829:         my $filepath;
1.1095    raeburn  3830:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3831:              $filepath = 'tmp/helprequests/'.$now;
                   3832:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3833:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3834:                          '_'.$env{'user.domain'}.'/pending';
                   3835:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3836:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3837:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3838:                 $docudom = $destudom;
                   3839:             } else {
                   3840:                 $docudom = $env{'user.domain'};
                   3841:             }
1.1172.2.96  raeburn  3842:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3843:                 $docuname = $destuname;
                   3844:             } else {
                   3845:                 $docuname = $env{'user.name'};
                   3846:             }
                   3847:             if (exists($env{'form.group'})) {
                   3848:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3849:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3850:             }
                   3851:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3852:             if ($context eq 'canceloverwrite') {
                   3853:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3854:                 if (-e  $tempfile) {
                   3855:                     my @info = stat($tempfile);
                   3856:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3857:                         unlink($tempfile);
                   3858:                     }
                   3859:                 }
                   3860:                 return;
1.523     raeburn  3861:             }
                   3862:         }
1.1090    raeburn  3863:         # Create the directory if not present
1.741     raeburn  3864:         my @parts=split(/\//,$filepath);
                   3865:         my $fullpath = $perlvar{'lonDaemons'};
                   3866:         for (my $i=0;$i<@parts;$i++) {
                   3867:             $fullpath .= '/'.$parts[$i];
                   3868:             if ((-e $fullpath)!=1) {
                   3869:                 mkdir($fullpath,0777);
                   3870:             }
                   3871:         }
1.1172.2.96  raeburn  3872:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3873:         print $fh $env{'form.'.$formname};
                   3874:         close($fh);
1.1090    raeburn  3875:         if ($context eq 'existingfile') {
                   3876:             my @info = stat($fullpath.'/'.$fname);
                   3877:             return ($fullpath.'/'.$fname,$info[9]);
                   3878:         } else {
                   3879:             return $fullpath.'/'.$fname;
                   3880:         }
1.523     raeburn  3881:     }
1.995     raeburn  3882:     if ($subdir eq 'scantron') {
                   3883:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3884:     } else {
1.995     raeburn  3885:         $fname="$subdir/$fname";
                   3886:     }
1.1090    raeburn  3887:     if ($context eq 'coursedoc') {
1.638     albertel 3888: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3889: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3890:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3891:             return &finishuserfileupload($docuname,$docudom,
                   3892: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3893: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3894:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3895:         } else {
1.1172.2.21  raeburn  3896:             if ($env{'form.folder'}) {
                   3897:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3898:             }
1.638     albertel 3899:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3900: 				       $fname,$formname,$parser,
1.1095    raeburn  3901: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3902:         }
1.719     banghart 3903:     } elsif (defined($destuname)) {
                   3904:         my $docuname=$destuname;
                   3905:         my $docudom=$destudom;
1.860     raeburn  3906: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3907: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3908:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3909:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3910:     } else {
1.638     albertel 3911:         my $docuname=$env{'user.name'};
                   3912:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3913:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3914:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3915:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3916:         }
1.860     raeburn  3917: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3918: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3919:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3920:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3921:     }
1.271     www      3922: }
                   3923: 
                   3924: sub finishuserfileupload {
1.860     raeburn  3925:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3926:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3927:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3928:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3929:   
1.860     raeburn  3930:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3931:     $file=$fname;
                   3932:     if ($fname=~m|/|) {
                   3933:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3934: 	$path.=$fnamepath.'/';
                   3935:     }
1.259     www      3936:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3937:     my $count;
                   3938:     for ($count=4;$count<=$#parts;$count++) {
                   3939:         $filepath.="/$parts[$count]";
                   3940:         if ((-e $filepath)!=1) {
                   3941: 	    mkdir($filepath,0777);
                   3942:         }
                   3943:     }
1.984     neumanie 3944: 
1.258     www      3945: # Save the file
                   3946:     {
1.1172.2.96  raeburn  3947: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3948: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3949: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3950: 	    return '/adm/notfound.html';
                   3951: 	}
1.1090    raeburn  3952:         if ($context eq 'overwrite') {
1.1117    foxr     3953:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3954:             my $target = $filepath.'/'.$file;
                   3955:             if (-e $source) {
                   3956:                 my @info = stat($source);
                   3957:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3958:                     unless (&File::Copy::move($source,$target)) {
                   3959:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3960:                         return "Moving from $source failed";
                   3961:                     }
                   3962:                 } else {
                   3963:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3964:                 }
                   3965:             } else {
                   3966:                 return "Temporary file: $source missing";
                   3967:             }
                   3968:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3969: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3970: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3971: 	    return '/adm/notfound.html';
                   3972: 	}
1.570     albertel 3973: 	close(FH);
1.1051    raeburn  3974:         if ($resizewidth && $resizeheight) {
                   3975:             my $mm = new File::MMagic;
                   3976:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3977:             if ($mime_type =~ m{^image/}) {
                   3978: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3979:             }  
1.977     amueller 3980: 	}
1.258     www      3981:     }
1.1152    raeburn  3982:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3983:         if (ref($mimetype)) {
                   3984:             if ($$mimetype eq '') {
                   3985:                 my $mm = new File::MMagic;
                   3986:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3987:                 $$mimetype = $type;
                   3988:             }
                   3989:         }
                   3990:     }
1.1172.2.109  raeburn  3991:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3992:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3993:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3994:                                                        $allfiles,$codebase);
                   3995:             unless ($parse_result eq 'ok') {
                   3996:                 &logthis('Failed to parse '.$filepath.$file.
                   3997: 	   	         ' for embedded media: '.$parse_result); 
                   3998:             }
1.637     raeburn  3999:         }
1.1172.2.109  raeburn  4000:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4001:         my $format = $env{'form.scantron_format'};
                   4002:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4003:     }
1.860     raeburn  4004:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4005:         my $input = $filepath.'/'.$file;
                   4006:         my $output = $filepath.'/'.'tn-'.$file;
                   4007:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4008:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4009:         system({$args[0]} @args);
1.860     raeburn  4010:         if (-e $filepath.'/'.'tn-'.$file) {
                   4011:             $fetchthumb  = 1; 
                   4012:         }
                   4013:     }
1.858     raeburn  4014:  
1.259     www      4015: # Notify homeserver to grep it
                   4016: #
1.984     neumanie 4017:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4018:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4019:     if ($fetchresult eq 'ok') {
1.860     raeburn  4020:         if ($fetchthumb) {
                   4021:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4022:             if ($thumbresult ne 'ok') {
                   4023:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4024:                          $docuhome.': '.$thumbresult);
                   4025:             }
                   4026:         }
1.259     www      4027: #
1.258     www      4028: # Return the URL to it
1.494     albertel 4029:         return '/uploaded/'.$path.$file;
1.263     www      4030:     } else {
1.494     albertel 4031:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4032: 		 ': '.$fetchresult);
1.263     www      4033:         return '/adm/notfound.html';
1.858     raeburn  4034:     }
1.493     albertel 4035: }
                   4036: 
1.637     raeburn  4037: sub extract_embedded_items {
1.961     raeburn  4038:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4039:     my @state = ();
1.1164    raeburn  4040:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4041:     my %javafiles = (
                   4042:                       codebase => '',
                   4043:                       code => '',
                   4044:                       archive => ''
                   4045:                     );
                   4046:     my %mediafiles = (
                   4047:                       src => '',
                   4048:                       movie => '',
                   4049:                      );
1.648     raeburn  4050:     my $p;
                   4051:     if ($content) {
                   4052:         $p = HTML::LCParser->new($content);
                   4053:     } else {
1.961     raeburn  4054:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4055:     }
1.641     albertel 4056:     while (my $t=$p->get_token()) {
1.640     albertel 4057: 	if ($t->[0] eq 'S') {
                   4058: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4059: 	    push(@state, $tagname);
1.648     raeburn  4060:             if (lc($tagname) eq 'allow') {
                   4061:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4062:             }
1.640     albertel 4063: 	    if (lc($tagname) eq 'img') {
                   4064: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4065: 	    }
1.886     albertel 4066: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4067:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4068: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4069:                 }
1.886     albertel 4070: 	    }
1.645     raeburn  4071:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4072:                 my $src;
1.645     raeburn  4073:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4074:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4075:                 } else {
1.1164    raeburn  4076:                     if ($attr->{'src'} ne '') {
                   4077:                         $src = $attr->{'src'};
                   4078:                         &add_filetype($allfiles,$src,'src');
                   4079:                     }
                   4080:                 }
                   4081:                 my $text = $p->get_trimmed_text();
                   4082:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4083:                     my @swfargs = split(/,/,$1);
                   4084:                     foreach my $item (@swfargs) {
                   4085:                         $item =~ s/["']//g;
                   4086:                         $item =~ s/^\s+//;
                   4087:                         $item =~ s/\s+$//;
                   4088:                     }
                   4089:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4090:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4091:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4092:                         } else {
                   4093:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4094:                         }
                   4095:                     }
1.645     raeburn  4096:                 }
                   4097:             }
                   4098:             if (lc($tagname) eq 'link') {
                   4099:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4100:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4101:                 }
                   4102:             }
1.640     albertel 4103: 	    if (lc($tagname) eq 'object' ||
                   4104: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4105: 		foreach my $item (keys(%javafiles)) {
                   4106: 		    $javafiles{$item} = '';
                   4107: 		}
1.1164    raeburn  4108:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4109:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4110:                 }
1.640     albertel 4111: 	    }
                   4112: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4113: 		my $name = lc($attr->{'name'});
                   4114: 		foreach my $item (keys(%javafiles)) {
                   4115: 		    if ($name eq $item) {
                   4116: 			$javafiles{$item} = $attr->{'value'};
                   4117: 			last;
                   4118: 		    }
                   4119: 		}
1.1164    raeburn  4120:                 my $pathfrom;
1.640     albertel 4121: 		foreach my $item (keys(%mediafiles)) {
                   4122: 		    if ($name eq $item) {
1.1164    raeburn  4123:                         $pathfrom = $attr->{'value'};
                   4124:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4125: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4126: 			last;
                   4127: 		    }
                   4128: 		}
1.1164    raeburn  4129:                 if ($name eq 'flashvars') {
                   4130:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4131:                 }
                   4132:                 if ($pathfrom ne '') {
                   4133:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4134:                                          $pathfrom);
                   4135:                 }
1.640     albertel 4136: 	    }
                   4137: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4138: 		foreach my $item (keys(%javafiles)) {
                   4139: 		    if ($attr->{$item}) {
                   4140: 			$javafiles{$item} = $attr->{$item};
                   4141: 			last;
                   4142: 		    }
                   4143: 		}
                   4144: 		foreach my $item (keys(%mediafiles)) {
                   4145: 		    if ($attr->{$item}) {
                   4146: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4147: 			last;
                   4148: 		    }
                   4149: 		}
1.1164    raeburn  4150:                 if (lc($tagname) eq 'embed') {
                   4151:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4152:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4153:                                              $attr->{'src'});
                   4154:                     }
                   4155:                 }
1.640     albertel 4156: 	    }
1.1172.2.35  raeburn  4157:             if (lc($tagname) eq 'iframe') {
                   4158:                 my $src = $attr->{'src'} ;
                   4159:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4160:                     &add_filetype($allfiles,$src,'src');
                   4161:                 } elsif ($src =~ m{^/}) {
                   4162:                     if ($env{'request.course.id'}) {
                   4163:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4164:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4165:                         my $url = &hreflocation('',$fullpath);
                   4166:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4167:                             my $relpath = $1;
                   4168:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4169:                                 &add_filetype($allfiles,$1,'src');
                   4170:                             }
                   4171:                         }
                   4172:                     }
                   4173:                 }
                   4174:             }
1.1164    raeburn  4175:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4176:                 pop(@state);
1.1164    raeburn  4177:             }
1.640     albertel 4178: 	} elsif ($t->[0] eq 'E') {
                   4179: 	    my ($tagname) = ($t->[1]);
                   4180: 	    if ($javafiles{'codebase'} ne '') {
                   4181: 		$javafiles{'codebase'} .= '/';
                   4182: 	    }  
                   4183: 	    if (lc($tagname) eq 'applet' ||
                   4184: 		lc($tagname) eq 'object' ||
                   4185: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4186: 		) {
                   4187: 		foreach my $item (keys(%javafiles)) {
                   4188: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4189: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4190: 			&add_filetype($allfiles,$file,$item);
                   4191: 		    }
                   4192: 		}
                   4193: 	    } 
                   4194: 	    pop @state;
                   4195: 	}
                   4196:     }
1.1164    raeburn  4197:     foreach my $id (sort(keys(%flashvars))) {
                   4198:         if ($shockwave{$id} ne '') {
                   4199:             my @pairs = split(/\&/,$flashvars{$id});
                   4200:             foreach my $pair (@pairs) {
                   4201:                 my ($key,$value) = split(/\=/,$pair);
                   4202:                 if ($key eq 'thumb') {
                   4203:                     &add_filetype($allfiles,$value,$key);
                   4204:                 } elsif ($key eq 'content') {
                   4205:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4206:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4207:                     if ($ext ne '') {
                   4208:                         &add_filetype($allfiles,$path.$value,$ext);
                   4209:                     }
                   4210:                 }
                   4211:             }
                   4212:         }
                   4213:     }
1.637     raeburn  4214:     return 'ok';
                   4215: }
                   4216: 
1.639     albertel 4217: sub add_filetype {
                   4218:     my ($allfiles,$file,$type)=@_;
                   4219:     if (exists($allfiles->{$file})) {
                   4220: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4221: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4222: 	}
                   4223:     } else {
                   4224: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4225:     }
                   4226: }
                   4227: 
1.1164    raeburn  4228: sub embedded_dependency {
                   4229:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4230:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4231:         if (($identifier ne '') &&
                   4232:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4233:             ($pathfrom ne '')) {
                   4234:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4235:             foreach my $dep (@{$related->{$identifier}}) {
                   4236:                 &add_filetype($allfiles,$path.$dep,'object');
                   4237:             }
                   4238:         }
                   4239:     }
                   4240:     return;
                   4241: }
                   4242: 
1.1172.2.109  raeburn  4243: sub bubblesheet_converter {
                   4244:     my ($cdom,$fullpath,$config,$format) = @_;
                   4245:     if ((&domain($cdom) ne '') &&
                   4246:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4247:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4248:         my (%csvcols,%csvoptions);
                   4249:         if (ref($config->{'fields'}) eq 'HASH') {
                   4250:             %csvcols = %{$config->{'fields'}};
                   4251:         }
                   4252:         if (ref($config->{'options'}) eq 'HASH') {
                   4253:             %csvoptions = %{$config->{'options'}};
                   4254:         }
                   4255:         my %csvbynum = reverse(%csvcols);
                   4256:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4257:         if (keys(%scantronconf)) {
                   4258:             my %bynum = (
                   4259:                           $scantronconf{CODEstart} => 'CODEstart',
                   4260:                           $scantronconf{IDstart}   => 'IDstart',
                   4261:                           $scantronconf{PaperID}   => 'PaperID',
                   4262:                           $scantronconf{FirstName} => 'FirstName',
                   4263:                           $scantronconf{LastName}  => 'LastName',
                   4264:                           $scantronconf{Qstart}    => 'Qstart',
                   4265:                         );
                   4266:             my @ordered;
                   4267:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4268:                 push(@ordered,$bynum{$item});
                   4269:             }
                   4270:             my %mapstart = (
                   4271:                               CODEstart => 'CODE',
                   4272:                               IDstart   => 'ID',
                   4273:                               PaperID   => 'PaperID',
                   4274:                               FirstName => 'FirstName',
                   4275:                               LastName  => 'LastName',
                   4276:                               Qstart    => 'FirstQuestion',
                   4277:                            );
                   4278:             my %maplength = (
                   4279:                               CODEstart => 'CODElength',
                   4280:                               IDstart   => 'IDlength',
                   4281:                               PaperID   => 'PaperIDlength',
                   4282:                               FirstName => 'FirstNamelength',
                   4283:                               LastName  => 'LastNamelength',
                   4284:             );
                   4285:             if (open(my $fh,'<',$fullpath)) {
                   4286:                 my $output;
                   4287:                 my %lettdig = &letter_to_digits();
                   4288:                 my %diglett = reverse(%lettdig);
                   4289:                 my $numletts = scalar(keys(%lettdig));
                   4290:                 my $num = 0;
                   4291:                 while (my $line=<$fh>) {
                   4292:                     $num ++;
                   4293:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4294:                     $line =~ s{[\r\n]+$}{};
                   4295:                     my %found;
                   4296:                     my @values = split(/,/,$line);
                   4297:                     my ($qstart,$record);
                   4298:                     for (my $i=0; $i<@values; $i++) {
                   4299:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4300:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4301:                             if ($values[$i] eq '') {
                   4302:                                 $values[$i] = $scantronconf{'Qoff'};
                   4303:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4304:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4305:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4306:                                 }
                   4307:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4308:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4309:                                     $values[$i] = $diglett{$values[$i]};
                   4310:                                 }
                   4311:                             } else {
                   4312:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4313:                                     my $digit;
                   4314:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4315:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4316:                                         if ($values[$i] eq 'J') {
                   4317:                                             $digit += $numletts;
                   4318:                                         }
                   4319:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4320:                                         $digit = $values[$i]-1;
                   4321:                                         if ($values[$i] eq '0') {
                   4322:                                             $digit += $numletts;
                   4323:                                         }
                   4324:                                     }
                   4325:                                     my $qval='';
                   4326:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4327:                                         if ($j == $digit) {
                   4328:                                             $qval .= $scantronconf{'Qon'};
                   4329:                                         } else {
                   4330:                                             $qval .= $scantronconf{'Qoff'};
                   4331:                                         }
                   4332:                                     }
                   4333:                                     $values[$i] = $qval;
                   4334:                                 }
                   4335:                             }
                   4336:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4337:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4338:                             }
                   4339:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4340:                             if ($numblank > 0) {
                   4341:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4342:                             }
                   4343:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4344:                                 $qstart = $i;
                   4345:                                 $found{$csvbynum{$i}} = $values[$i];
                   4346:                             } else {
                   4347:                                 $found{'FirstQuestion'} .= $values[$i];
                   4348:                             }
                   4349:                         } elsif (exists($csvbynum{$i})) {
                   4350:                             if ($csvoptions{'rem'}) {
                   4351:                                 $values[$i] =~ s/^\s+//;
                   4352:                             }
                   4353:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4354:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4355:                                     $values[$i] = '0'.$values[$i];
                   4356:                                 }
                   4357:                             }
                   4358:                             $found{$csvbynum{$i}} = $values[$i];
                   4359:                         }
                   4360:                     }
                   4361:                     foreach my $item (@ordered) {
                   4362:                         my $currlength = 1+length($record);
                   4363:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4364:                         if ($numspaces > 0) {
                   4365:                             $record .= (' ' x $numspaces);
                   4366:                         }
                   4367:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4368:                             unless ($item eq 'Qstart') {
                   4369:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4370:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4371:                                 }
                   4372:                             }
                   4373:                             $record .= $found{$mapstart{$item}};
                   4374:                         }
                   4375:                     }
                   4376:                     $output .= "$record\n";
                   4377:                 }
                   4378:                 close($fh);
                   4379:                 if ($output) {
                   4380:                     if (open(my $fh,'>',$fullpath)) {
                   4381:                         print $fh $output;
                   4382:                         close($fh);
                   4383:                     }
                   4384:                 }
                   4385:             }
                   4386:         }
                   4387:         return;
                   4388:     }
                   4389: }
                   4390: 
                   4391: sub letter_to_digits {
                   4392:     my %lettdig = (
                   4393:                     A => 1,
                   4394:                     B => 2,
                   4395:                     C => 3,
                   4396:                     D => 4,
                   4397:                     E => 5,
                   4398:                     F => 6,
                   4399:                     G => 7,
                   4400:                     H => 8,
                   4401:                     I => 9,
                   4402:                     J => 0,
                   4403:                   );
                   4404:     return %lettdig;
                   4405: }
                   4406: 
                   4407: sub get_scantron_config {
                   4408:     my ($which,$cdom) = @_;
                   4409:     my @lines = &get_scantronformat_file($cdom);
                   4410:     my %config;
                   4411:     #FIXME probably should move to XML it has already gotten a bit much now
                   4412:     foreach my $line (@lines) {
                   4413:         my ($name,$descrip)=split(/:/,$line);
                   4414:         if ($name ne $which ) { next; }
                   4415:         chomp($line);
                   4416:         my @config=split(/:/,$line);
                   4417:         $config{'name'}=$config[0];
                   4418:         $config{'description'}=$config[1];
                   4419:         $config{'CODElocation'}=$config[2];
                   4420:         $config{'CODEstart'}=$config[3];
                   4421:         $config{'CODElength'}=$config[4];
                   4422:         $config{'IDstart'}=$config[5];
                   4423:         $config{'IDlength'}=$config[6];
                   4424:         $config{'Qstart'}=$config[7];
                   4425:         $config{'Qlength'}=$config[8];
                   4426:         $config{'Qoff'}=$config[9];
                   4427:         $config{'Qon'}=$config[10];
                   4428:         $config{'PaperID'}=$config[11];
                   4429:         $config{'PaperIDlength'}=$config[12];
                   4430:         $config{'FirstName'}=$config[13];
                   4431:         $config{'FirstNamelength'}=$config[14];
                   4432:         $config{'LastName'}=$config[15];
                   4433:         $config{'LastNamelength'}=$config[16];
                   4434:         $config{'BubblesPerRow'}=$config[17];
                   4435:         last;
                   4436:     }
                   4437:     return %config;
                   4438: }
                   4439: 
                   4440: sub get_scantronformat_file {
                   4441:     my ($cdom) = @_;
                   4442:     if ($cdom eq '') {
                   4443:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4444:     }
                   4445:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4446:     my $gottab = 0;
                   4447:     my @lines;
                   4448:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4449:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4450:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4451:             if ($formatfile ne '-1') {
                   4452:                 @lines = split("\n",$formatfile,-1);
                   4453:                 $gottab = 1;
                   4454:             }
                   4455:         }
                   4456:     }
                   4457:     if (!$gottab) {
                   4458:         my $confname = $cdom.'-domainconfig';
                   4459:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4460:         my $formatfile = &getfile($default);
                   4461:         if ($formatfile ne '-1') {
                   4462:             @lines = split("\n",$formatfile,-1);
                   4463:             $gottab = 1;
                   4464:         }
                   4465:     }
                   4466:     if (!$gottab) {
                   4467:         my @domains = &current_machine_domains();
                   4468:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4469:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4470:                 @lines = <$fh>;
                   4471:                 close($fh);
                   4472:             }
                   4473:         } else {
                   4474:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4475:                 @lines = <$fh>;
                   4476:                 close($fh);
                   4477:             }
                   4478:         }
                   4479:     }
                   4480:     return @lines;
                   4481: }
                   4482: 
1.493     albertel 4483: sub removeuploadedurl {
1.984     neumanie 4484:     my ($url)=@_;	
                   4485:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4486:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4487: }
                   4488: 
                   4489: sub removeuserfile {
                   4490:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4491:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4492:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4493:     if ($result eq 'ok') {	
1.798     raeburn  4494:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4495:             my $metafile = $fname.'.meta';
                   4496:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4497: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4498:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4499:             my $sqlresult = 
1.823     albertel 4500:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4501:                                         'portfolio_metadata',$group,
                   4502:                                         'delete');
1.798     raeburn  4503:         }
                   4504:     }
                   4505:     return $result;
1.257     www      4506: }
1.15      www      4507: 
1.530     albertel 4508: sub mkdiruserfile {
                   4509:     my ($docuname,$docudom,$dir)=@_;
                   4510:     my $home=&homeserver($docuname,$docudom);
                   4511:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4512: }
                   4513: 
1.531     albertel 4514: sub renameuserfile {
                   4515:     my ($docuname,$docudom,$old,$new)=@_;
                   4516:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4517:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4518:                         &escape("$old").':'.&escape("$new"),$home);
                   4519:     if ($result eq 'ok') {
                   4520:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4521:             my $oldmeta = $old.'.meta';
                   4522:             my $newmeta = $new.'.meta';
                   4523:             my $metaresult = 
                   4524:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4525: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4526:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4527:             my $sqlresult = 
1.823     albertel 4528:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4529:                                         'portfolio_metadata',$group,
                   4530:                                         'delete');
1.798     raeburn  4531:         }
                   4532:     }
                   4533:     return $result;
1.531     albertel 4534: }
                   4535: 
1.14      www      4536: # ------------------------------------------------------------------------- Log
                   4537: 
                   4538: sub log {
                   4539:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4540:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4541: }
                   4542: 
                   4543: # ------------------------------------------------------------------ Course Log
1.352     www      4544: #
                   4545: # This routine flushes several buffers of non-mission-critical nature
                   4546: #
1.157     www      4547: 
                   4548: sub flushcourselogs {
1.352     www      4549:     &logthis('Flushing log buffers');
                   4550: #
                   4551: # course logs
                   4552: # This is a log of all transactions in a course, which can be used
                   4553: # for data mining purposes
                   4554: #
                   4555: # It also collects the courseid database, which lists last transaction
                   4556: # times and course titles for all courseids
                   4557: #
                   4558:     my %courseidbuffer=();
1.921     raeburn  4559:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4560:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4561: 		          &escape($courselogs{$crsid}),
                   4562: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4563: 	    delete $courselogs{$crsid};
                   4564:         } else {
                   4565:             &logthis('Failed to flush log buffer for '.$crsid);
                   4566:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4567:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4568:                         " exceeded maximum size, deleting.</font>");
                   4569:                delete $courselogs{$crsid};
                   4570:             }
1.352     www      4571:         }
1.920     raeburn  4572:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4573:             'description' => $coursedescrbuf{$crsid},
                   4574:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4575:             'type'        => $coursetypebuf{$crsid},
                   4576:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4577:         };
1.191     harris41 4578:     }
1.352     www      4579: #
                   4580: # Write course id database (reverse lookup) to homeserver of courses 
                   4581: # Is used in pickcourse
                   4582: #
1.840     albertel 4583:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4584:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4585:                                     $courseidbuffer{$crs_home},
                   4586:                                     $crs_home,'timeonly');
1.352     www      4587:     }
                   4588: #
                   4589: # File accesses
                   4590: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4591: #
1.449     matthew  4592:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4593:         if ($entry =~ /___count$/) {
                   4594:             my ($dom,$name);
1.807     albertel 4595:             ($dom,$name,undef)=
1.811     albertel 4596: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4597:             if (! defined($dom) || $dom eq '' || 
                   4598:                 ! defined($name) || $name eq '') {
1.620     albertel 4599:                 my $cid = $env{'request.course.id'};
                   4600:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4601:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4602:             }
1.450     matthew  4603:             my $value = $accesshash{$entry};
                   4604:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4605:             my %temphash=($url => $value);
1.449     matthew  4606:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4607:             if ($result eq 'ok') {
                   4608:                 delete $accesshash{$entry};
                   4609:             }
                   4610:         } else {
1.811     albertel 4611:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4612:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4613:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4614:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4615:                 delete $accesshash{$entry};
                   4616:             }
1.185     www      4617:         }
1.191     harris41 4618:     }
1.352     www      4619: #
                   4620: # Roles
                   4621: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4622: #
1.800     albertel 4623:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4624:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4625: 	    split(/\:/,$entry);
                   4626:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4627:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4628:                 $rudom,$runame) eq 'ok') {
                   4629: 	    delete $userrolehash{$entry};
                   4630:         }
                   4631:     }
1.662     raeburn  4632: #
1.1172.2.90  raeburn  4633: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4634: #
                   4635:     my %domrolebuffer = ();
1.1000    raeburn  4636:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4637:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4638:         if ($domrolebuffer{$rudom}) {
                   4639:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4640:                       '='.&escape($domainrolehash{$entry});
                   4641:         } else {
                   4642:             $domrolebuffer{$rudom}.=&escape($entry).
                   4643:                       '='.&escape($domainrolehash{$entry});
                   4644:         }
                   4645:         delete $domainrolehash{$entry};
                   4646:     }
                   4647:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4648:         my %servers;
                   4649:         if (defined(&domain($dom,'primary'))) {
                   4650:             my $primary=&domain($dom,'primary');
                   4651:             my $hostname=&hostname($primary);
                   4652:             $servers{$primary} = $hostname;
                   4653:         } else {
                   4654:             %servers = &get_servers($dom,'library');
                   4655:         }
1.841     albertel 4656: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4657: 	    if (&reply('domroleput:'.$dom.':'.
                   4658: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4659: 	        last;
                   4660: 	    } else {
1.841     albertel 4661: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4662: 	    }
1.662     raeburn  4663:         }
                   4664:     }
1.186     www      4665:     $dumpcount++;
1.157     www      4666: }
                   4667: 
                   4668: sub courselog {
                   4669:     my $what=shift;
1.158     www      4670:     $what=time.':'.$what;
1.620     albertel 4671:     unless ($env{'request.course.id'}) { return ''; }
                   4672:     $coursedombuf{$env{'request.course.id'}}=
                   4673:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4674:     $coursenumbuf{$env{'request.course.id'}}=
                   4675:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4676:     $coursehombuf{$env{'request.course.id'}}=
                   4677:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4678:     $coursedescrbuf{$env{'request.course.id'}}=
                   4679:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4680:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4681:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4682:     $courseownerbuf{$env{'request.course.id'}}=
                   4683:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4684:     $coursetypebuf{$env{'request.course.id'}}=
                   4685:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4686:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4687: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4688:     } else {
1.620     albertel 4689: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4690:     }
1.620     albertel 4691:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4692: 	&flushcourselogs();
                   4693:     }
1.158     www      4694: }
                   4695: 
                   4696: sub courseacclog {
                   4697:     my $fnsymb=shift;
1.620     albertel 4698:     unless ($env{'request.course.id'}) { return ''; }
                   4699:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4700:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4701:         $what.=':POST';
1.583     matthew  4702:         # FIXME: Probably ought to escape things....
1.800     albertel 4703: 	foreach my $key (keys(%env)) {
                   4704:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4705:                 my $formitem = $1;
                   4706:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4707:                     $what.=':'.$formitem.'='.$env{$key};
                   4708:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4709:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4710:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4711:                     } else {
                   4712:                         $what.=':'.$formitem.'='.$env{$key};
                   4713:                     }
1.975     raeburn  4714:                 }
1.158     www      4715:             }
1.191     harris41 4716:         }
1.583     matthew  4717:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4718:         # FIXME: We should not be depending on a form parameter that someone
                   4719:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4720:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4721:             $what.= ':POST';
                   4722:             # FIXME: Probably ought to escape things....
                   4723:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4724:                                  'crsdiscuss') {
1.620     albertel 4725:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4726:             }
                   4727:         }
1.158     www      4728:     }
                   4729:     &courselog($what);
1.149     www      4730: }
                   4731: 
1.185     www      4732: sub countacc {
                   4733:     my $url=&declutter(shift);
1.458     matthew  4734:     return if (! defined($url) || $url eq '');
1.620     albertel 4735:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4736: #
                   4737: # Mark that this url was used in this course
                   4738: #
1.620     albertel 4739:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4740: #
                   4741: # Increase the access count for this resource in this child process
                   4742: #
1.281     www      4743:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4744:     $accesshash{$key}++;
1.185     www      4745: }
1.349     www      4746: 
1.361     www      4747: sub linklog {
                   4748:     my ($from,$to)=@_;
                   4749:     $from=&declutter($from);
                   4750:     $to=&declutter($to);
                   4751:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4752:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4753: }
1.1160    www      4754: 
                   4755: sub statslog {
                   4756:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4757:     if ($users<2) { return; }
                   4758:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4759:             'course'       => $env{'request.course.id'},
                   4760:             'sections'     => '"all"',
                   4761:             'num_students' => $users,
                   4762:             'part'         => $part,
                   4763:             'symb'         => $symb,
                   4764:             'mean_tries'   => $av_attempts,
                   4765:             'deg_of_diff'  => $degdiff});
                   4766:     foreach my $key (keys(%dynstore)) {
                   4767:         $accesshash{$key}=$dynstore{$key};
                   4768:     }
                   4769: }
1.361     www      4770:   
1.349     www      4771: sub userrolelog {
                   4772:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4773:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4774:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4775:        $userrolehash
                   4776:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4777:                     =$tend.':'.$tstart;
1.662     raeburn  4778:     }
1.1169    droeschl 4779:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4780:        $userrolehash
                   4781:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4782:                     =$tend.':'.$tstart;
                   4783:     }
1.1172.2.90  raeburn  4784:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4785:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4786:        $domainrolehash
                   4787:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4788:                     = $tend.':'.$tstart;
                   4789:     }
1.351     www      4790: }
                   4791: 
1.957     raeburn  4792: sub courserolelog {
                   4793:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4794:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4795:         my $cdom = $1;
                   4796:         my $cnum = $2;
                   4797:         my $sec = $3;
                   4798:         my $namespace = 'rolelog';
                   4799:         my %storehash = (
                   4800:                            role    => $trole,
                   4801:                            start   => $tstart,
                   4802:                            end     => $tend,
                   4803:                            selfenroll => $selfenroll,
                   4804:                            context    => $context,
                   4805:                         );
                   4806:         if ($trole eq 'gr') {
                   4807:             $namespace = 'groupslog';
                   4808:             $storehash{'group'} = $sec;
                   4809:         } else {
                   4810:             $storehash{'section'} = $sec;
                   4811:         }
                   4812:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4813:                    $domain,$cnum,$cdom);
                   4814:         if (($trole ne 'st') || ($sec ne '')) {
                   4815:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4816:         }
                   4817:     }
                   4818:     return;
                   4819: }
                   4820: 
1.1172.2.9  raeburn  4821: sub domainrolelog {
                   4822:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4823:     if ($area =~ m{^/($match_domain)/$}) {
                   4824:         my $cdom = $1;
                   4825:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4826:         my $namespace = 'rolelog';
                   4827:         my %storehash = (
                   4828:                            role    => $trole,
                   4829:                            start   => $tstart,
                   4830:                            end     => $tend,
                   4831:                            context => $context,
                   4832:                         );
                   4833:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4834:                    $domain,$domconfiguser,$cdom);
                   4835:     }
                   4836:     return;
                   4837: 
                   4838: }
                   4839: 
                   4840: sub coauthorrolelog {
                   4841:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4842:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4843:         my $audom = $1;
                   4844:         my $auname = $2;
                   4845:         my $namespace = 'rolelog';
                   4846:         my %storehash = (
                   4847:                            role    => $trole,
                   4848:                            start   => $tstart,
                   4849:                            end     => $tend,
                   4850:                            context => $context,
                   4851:                         );
                   4852:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4853:                    $domain,$auname,$audom);
                   4854:     }
                   4855:     return;
                   4856: }
                   4857: 
1.351     www      4858: sub get_course_adv_roles {
1.948     raeburn  4859:     my ($cid,$codes) = @_;
1.620     albertel 4860:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4861:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4862:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4863:     my %nothide=();
1.800     albertel 4864:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4865:         if ($user !~ /:/) {
                   4866: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4867:         } else {
                   4868:             $nothide{$user}=1;
                   4869:         }
1.470     www      4870:     }
1.1172.2.23  raeburn  4871:     my @possdoms = ($coursehash{'domain'});
                   4872:     if ($coursehash{'checkforpriv'}) {
                   4873:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4874:     }
1.351     www      4875:     my %returnhash=();
                   4876:     my %dumphash=
                   4877:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4878:     my $now=time;
1.997     raeburn  4879:     my %privileged;
1.1000    raeburn  4880:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4881: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4882:         if (($tstart) && ($tstart<0)) { next; }
                   4883:         if (($tend) && ($tend<$now)) { next; }
                   4884:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4885:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4886: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4887:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4888:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4889: 	if ($role eq 'cr') { next; }
1.948     raeburn  4890:         if ($codes) {
                   4891:             if ($section) { $role .= ':'.$section; }
                   4892:             if ($returnhash{$role}) {
                   4893:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4894:             } else {
                   4895:                 $returnhash{$role}=$username.':'.$domain;
                   4896:             }
1.351     www      4897:         } else {
1.988     raeburn  4898:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4899:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4900:             if ($returnhash{$key}) {
                   4901: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4902:             } else {
                   4903:                 $returnhash{$key}=$username.':'.$domain;
                   4904:             }
1.351     www      4905:         }
1.948     raeburn  4906:     }
1.400     www      4907:     return %returnhash;
                   4908: }
                   4909: 
                   4910: sub get_my_roles {
1.937     raeburn  4911:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4912:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4913:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4914:     my (%dumphash,%nothide);
1.1086    raeburn  4915:     if ($context eq 'userroles') {
1.1166    raeburn  4916:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4917:     } else {
1.1172.2.23  raeburn  4918:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4919:         if ($hidepriv) {
                   4920:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4921:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4922:                 if ($user !~ /:/) {
                   4923:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4924:                 } else {
                   4925:                     $nothide{$user} = 1;
                   4926:                 }
                   4927:             }
                   4928:         }
1.858     raeburn  4929:     }
1.400     www      4930:     my %returnhash=();
                   4931:     my $now=time;
1.999     raeburn  4932:     my %privileged;
1.800     albertel 4933:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4934:         my ($role,$tend,$tstart);
                   4935:         if ($context eq 'userroles') {
1.1149    raeburn  4936:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4937: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4938:         } else {
                   4939:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4940:         }
1.400     www      4941:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4942:         my $status = 'active';
1.939     raeburn  4943:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4944:             $status = 'previous';
                   4945:         } 
                   4946:         if (($tstart) && ($now<$tstart)) {
                   4947:             $status = 'future';
                   4948:         }
                   4949:         if (ref($types) eq 'ARRAY') {
                   4950:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4951:                 next;
                   4952:             } 
                   4953:         } else {
                   4954:             if ($status ne 'active') {
                   4955:                 next;
                   4956:             }
                   4957:         }
1.867     raeburn  4958:         my ($rolecode,$username,$domain,$section,$area);
                   4959:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4960:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4961:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4962:         } else {
                   4963:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4964:         }
1.832     raeburn  4965:         if (ref($roledoms) eq 'ARRAY') {
                   4966:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4967:                 next;
                   4968:             }
                   4969:         }
                   4970:         if (ref($roles) eq 'ARRAY') {
                   4971:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4972:                 if ($role =~ /^cr\//) {
                   4973:                     if (!grep(/^cr$/,@{$roles})) {
                   4974:                         next;
                   4975:                     }
1.1104    raeburn  4976:                 } elsif ($role =~ /^gr\//) {
                   4977:                     if (!grep(/^gr$/,@{$roles})) {
                   4978:                         next;
                   4979:                     }
1.922     raeburn  4980:                 } else {
                   4981:                     next;
                   4982:                 }
1.832     raeburn  4983:             }
1.867     raeburn  4984:         }
1.937     raeburn  4985:         if ($hidepriv) {
1.1172.2.23  raeburn  4986:             my @privroles = ('dc','su');
1.999     raeburn  4987:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4988:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4989:             } else {
1.1172.2.23  raeburn  4990:                 my $possdoms = [$domain];
                   4991:                 if (ref($roledoms) eq 'ARRAY') {
                   4992:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4993:                 }
1.1172.2.23  raeburn  4994:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4995:                     if (!$nothide{$username.':'.$domain}) {
                   4996:                         next;
                   4997:                     }
                   4998:                 }
1.937     raeburn  4999:             }
                   5000:         }
1.933     raeburn  5001:         if ($withsec) {
                   5002:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5003:                 $tstart.':'.$tend;
                   5004:         } else {
                   5005:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5006:         }
1.832     raeburn  5007:     }
1.373     www      5008:     return %returnhash;
1.399     www      5009: }
                   5010: 
1.1172.2.89  raeburn  5011: sub get_all_adhocroles {
                   5012:     my ($dom) = @_;
                   5013:     my @roles_by_num = ();
                   5014:     my %domdefaults = &get_domain_defaults($dom);
                   5015:     my (%description,%access_in_dom,%access_info);
                   5016:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5017:         my $count = 0;
                   5018:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5019:         my %ordered;
                   5020:         foreach my $role (sort(keys(%domcurrent))) {
                   5021:             my ($order,$desc,$access_in_dom);
                   5022:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5023:                 $order = $domcurrent{$role}{'order'};
                   5024:                 $desc = $domcurrent{$role}{'desc'};
                   5025:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5026:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5027:             }
                   5028:             if ($order eq '') {
                   5029:                 $order = $count;
                   5030:             }
                   5031:             $ordered{$order} = $role;
                   5032:             if ($desc ne '') {
                   5033:                 $description{$role} = $desc;
                   5034:             } else {
                   5035:                 $description{$role}= $role;
                   5036:             }
                   5037:             $count++;
                   5038:         }
                   5039:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5040:             push(@roles_by_num,$ordered{$item});
                   5041:         }
                   5042:     }
                   5043:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5044: }
                   5045: 
                   5046: sub get_my_adhocroles {
                   5047:     my ($cid,$checkreg) = @_;
                   5048:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5049:     if ($env{'request.course.id'} eq $cid) {
                   5050:         $cdom = $env{'course.'.$cid.'.domain'};
                   5051:         $cnum = $env{'course.'.$cid.'.num'};
                   5052:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5053:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5054:         $cdom = $1;
                   5055:         $cnum = $2;
                   5056:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5057:                                      $cdom,$cnum);
                   5058:     }
                   5059:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5060:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5061:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5062:         if ($rosterhash{$user} ne '') {
                   5063:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5064:             return ([],{}) if ($type eq 'auto');
                   5065:         }
                   5066:     }
                   5067:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5068:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5069:             my $then=$env{'user.login.time'};
                   5070:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5071:             if (!$update) {
                   5072:                 $update = $then;
                   5073:             }
                   5074:             my @liveroles;
                   5075:             foreach my $role ('dh','da') {
                   5076:                 if ($env{"user.role.$role./$cdom/"}) {
                   5077:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5078:                     my $limit = $update;
                   5079:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5080:                         $limit = $then;
                   5081:                     }
                   5082:                     my $activerole = 1;
                   5083:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5084:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5085:                     if ($activerole) {
                   5086:                         push(@liveroles,$role);
                   5087:                     }
                   5088:                 }
                   5089:             }
                   5090:             if (@liveroles) {
1.1172.2.89  raeburn  5091:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5092:                     my ($accessref,$accessinfo,%access_in_dom);
                   5093:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5094:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5095:                         if (@{$roles_by_num}) {
                   5096:                             my %settings;
                   5097:                             if ($env{'request.course.id'} eq $cid) {
                   5098:                                 foreach my $envkey (keys(%env)) {
                   5099:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5100:                                         $settings{$1} = $env{$envkey};
                   5101:                                     }
                   5102:                                 }
                   5103:                             } else {
                   5104:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5105:                             }
                   5106:                             my %setincrs;
                   5107:                             if ($settings{'internal.adhocaccess'}) {
                   5108:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5109:                             }
                   5110:                             my @statuses;
                   5111:                             if ($env{'environment.inststatus'}) {
                   5112:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5113:                             }
                   5114:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5115:                             if (ref($accessref) eq 'HASH') {
                   5116:                                 %access_in_dom = %{$accessref};
                   5117:                             }
                   5118:                             foreach my $role (@{$roles_by_num}) {
                   5119:                                 my ($curraccess,@okstatus,@personnel);
                   5120:                                 if ($setincrs{$role}) {
                   5121:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5122:                                     if ($curraccess eq 'status') {
                   5123:                                         @okstatus = split(/\&/,$rest);
                   5124:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5125:                                         @personnel = split(/\&/,$rest);
                   5126:                                     }
                   5127:                                 } else {
                   5128:                                     $curraccess = $access_in_dom{$role};
                   5129:                                     if (ref($accessinfo) eq 'HASH') {
                   5130:                                         if ($curraccess eq 'status') {
                   5131:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5132:                                                 @okstatus = @{$accessinfo->{$role}};
                   5133:                                             }
                   5134:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5135:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5136:                                                 @personnel = @{$accessinfo->{$role}};
                   5137:                                             }
                   5138:                                         }
                   5139:                                     }
                   5140:                                 }
                   5141:                                 if ($curraccess eq 'none') {
                   5142:                                     next;
                   5143:                                 } elsif ($curraccess eq 'all') {
                   5144:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5145:                                 } elsif ($curraccess eq 'dh') {
                   5146:                                     if (grep(/^dh$/,@liveroles)) {
                   5147:                                         push(@possroles,$role);
                   5148:                                     } else {
                   5149:                                         next;
                   5150:                                     }
                   5151:                                 } elsif ($curraccess eq 'da') {
                   5152:                                     if (grep(/^da$/,@liveroles)) {
                   5153:                                         push(@possroles,$role);
                   5154:                                     } else {
                   5155:                                         next;
                   5156:                                     }
1.1172.2.89  raeburn  5157:                                 } elsif ($curraccess eq 'status') {
                   5158:                                     if (@okstatus) {
                   5159:                                         if (!@statuses) {
                   5160:                                             if (grep(/^default$/,@okstatus)) {
                   5161:                                                 push(@possroles,$role);
                   5162:                                             }
                   5163:                                         } else {
                   5164:                                             foreach my $status (@okstatus) {
                   5165:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5166:                                                     push(@possroles,$role);
                   5167:                                                     last;
                   5168:                                                 }
                   5169:                                             }
                   5170:                                         }
                   5171:                                     }
                   5172:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5173:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5174:                                         if ($curraccess eq 'exc') {
                   5175:                                             push(@possroles,$role);
                   5176:                                         }
                   5177:                                     } elsif ($curraccess eq 'inc') {
                   5178:                                         push(@possroles,$role);
                   5179:                                     }
                   5180:                                 }
                   5181:                             }
                   5182:                         }
                   5183:                     }
                   5184:                 }
                   5185:             }
                   5186:         }
                   5187:     }
                   5188:     unless (ref($description) eq 'HASH') {
                   5189:         if (ref($roles_by_num) eq 'ARRAY') {
                   5190:             my %desc;
                   5191:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5192:             $description = \%desc;
                   5193:         } else {
                   5194:             $description = {};
                   5195:         }
                   5196:     }
                   5197:     return (\@possroles,$description);
                   5198: }
                   5199: 
1.399     www      5200: # ----------------------------------------------------- Frontpage Announcements
                   5201: #
                   5202: #
                   5203: 
                   5204: sub postannounce {
                   5205:     my ($server,$text)=@_;
1.844     albertel 5206:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5207:     unless ($text=~/\w/) { $text=''; }
                   5208:     return &reply('setannounce:'.&escape($text),$server);
                   5209: }
                   5210: 
                   5211: sub getannounce {
1.448     albertel 5212: 
1.1172.2.96  raeburn  5213:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5214: 	my $announcement='';
1.800     albertel 5215: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5216: 	close($fh);
1.399     www      5217: 	if ($announcement=~/\w/) { 
                   5218: 	    return 
                   5219:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5220:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5221: 	} else {
                   5222: 	    return '';
                   5223: 	}
                   5224:     } else {
                   5225: 	return '';
                   5226:     }
1.351     www      5227: }
1.353     www      5228: 
                   5229: # ---------------------------------------------------------- Course ID routines
                   5230: # Deal with domain's nohist_courseid.db files
                   5231: #
                   5232: 
                   5233: sub courseidput {
1.921     raeburn  5234:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5235:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5236:     my $outcome;
                   5237:     if ($caller eq 'timeonly') {
                   5238:         my $cids = '';
                   5239:         foreach my $item (keys(%$storehash)) {
                   5240:             $cids.=&escape($item).'&';
                   5241:         }
                   5242:         $cids=~s/\&$//;
                   5243:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5244:                           $coursehome);       
                   5245:     } else {
                   5246:         my $items = '';
                   5247:         foreach my $item (keys(%$storehash)) {
                   5248:             $items.= &escape($item).'='.
                   5249:                      &freeze_escape($$storehash{$item}).'&';
                   5250:         }
                   5251:         $items=~s/\&$//;
                   5252:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5253:                           $coursehome);
1.918     raeburn  5254:     }
                   5255:     if ($outcome eq 'unknown_cmd') {
                   5256:         my $what;
                   5257:         foreach my $cid (keys(%$storehash)) {
                   5258:             $what .= &escape($cid).'=';
1.921     raeburn  5259:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5260:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5261:             }
                   5262:             $what =~ s/\:$/&/;
                   5263:         }
                   5264:         $what =~ s/\&$//;  
                   5265:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5266:     } else {
                   5267:         return $outcome;
                   5268:     }
1.353     www      5269: }
                   5270: 
                   5271: sub courseiddump {
1.921     raeburn  5272:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5273:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5274:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5275:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5276:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5277:     my $as_hash = 1;
                   5278:     my %returnhash;
                   5279:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5280:     my %libserv = &all_library();
                   5281:     foreach my $tryserver (keys(%libserv)) {
                   5282:         if ( (  $hostidflag == 1 
                   5283: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5284: 	     || (!defined($hostidflag)) ) {
                   5285: 
1.918     raeburn  5286: 	    if (($domfilter eq '') ||
                   5287: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5288:                 my $rep;
                   5289:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5290:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5291:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5292:                                 &escape($descfilter), &escape($instcodefilter),
                   5293:                                 &escape($ownerfilter), &escape($coursefilter),
                   5294:                                 &escape($typefilter), &escape($regexp_ok),
                   5295:                                 $as_hash, &escape($selfenrollonly),
                   5296:                                 &escape($catfilter), $showhidden, $caller,
                   5297:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5298:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5299:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5300:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5301:                 } else {
                   5302:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5303:                              $sincefilter.':'.&escape($descfilter).':'.
                   5304:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5305:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5306:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5307:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5308:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5309:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5310:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5311:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5312:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5313:                 }
                   5314: 
1.918     raeburn  5315:                 my @pairs=split(/\&/,$rep);
                   5316:                 foreach my $item (@pairs) {
                   5317:                     my ($key,$value)=split(/\=/,$item,2);
                   5318:                     $key = &unescape($key);
                   5319:                     next if ($key =~ /^error: 2 /);
                   5320:                     my $result = &thaw_unescape($value);
                   5321:                     if (ref($result) eq 'HASH') {
                   5322:                         $returnhash{$key}=$result;
                   5323:                     } else {
1.921     raeburn  5324:                         my @responses = split(/:/,$value);
                   5325:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5326:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5327:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5328:                         }
1.1008    raeburn  5329:                     }
1.353     www      5330:                 }
                   5331:             }
                   5332:         }
                   5333:     }
                   5334:     return %returnhash;
                   5335: }
                   5336: 
1.1055    raeburn  5337: sub courselastaccess {
                   5338:     my ($cdom,$cnum,$hostidref) = @_;
                   5339:     my %returnhash;
                   5340:     if ($cdom && $cnum) {
                   5341:         my $chome = &homeserver($cnum,$cdom);
                   5342:         if ($chome ne 'no_host') {
                   5343:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5344:             &extract_lastaccess(\%returnhash,$rep);
                   5345:         }
                   5346:     } else {
                   5347:         if (!$cdom) { $cdom=''; }
                   5348:         my %libserv = &all_library();
                   5349:         foreach my $tryserver (keys(%libserv)) {
                   5350:             if (ref($hostidref) eq 'ARRAY') {
                   5351:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5352:             } 
                   5353:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5354:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5355:                 &extract_lastaccess(\%returnhash,$rep);
                   5356:             }
                   5357:         }
                   5358:     }
                   5359:     return %returnhash;
                   5360: }
                   5361: 
                   5362: sub extract_lastaccess {
                   5363:     my ($returnhash,$rep) = @_;
                   5364:     if (ref($returnhash) eq 'HASH') {
                   5365:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5366:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5367:                  $rep eq '') {
                   5368:             my @pairs=split(/\&/,$rep);
                   5369:             foreach my $item (@pairs) {
                   5370:                 my ($key,$value)=split(/\=/,$item,2);
                   5371:                 $key = &unescape($key);
                   5372:                 next if ($key =~ /^error: 2 /);
                   5373:                 $returnhash->{$key} = &thaw_unescape($value);
                   5374:             }
                   5375:         }
                   5376:     }
                   5377:     return;
                   5378: }
                   5379: 
1.658     raeburn  5380: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5381: 
                   5382: sub dcmailput {
1.685     raeburn  5383:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5384:     my $status = &Apache::lonnet::critical(
1.740     www      5385:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5386:        &escape($message),$server);
1.662     raeburn  5387:     return $status;
                   5388: }
                   5389: 
1.658     raeburn  5390: sub dcmaildump {
                   5391:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5392:     my %returnhash=();
1.846     albertel 5393: 
                   5394:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5395:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5396:                                                          &escape($enddate).':';
                   5397: 	my @esc_senders=map { &escape($_)} @$senders;
                   5398: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5399: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5400:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5401:             if (($key) && ($value)) {
                   5402:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5403:             }
                   5404:         }
                   5405:     }
                   5406:     return %returnhash;
                   5407: }
1.662     raeburn  5408: # ---------------------------------------------------------- Domain roles
                   5409: 
                   5410: sub get_domain_roles {
                   5411:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5412:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5413:         $startdate = '.';
                   5414:     }
1.1018    raeburn  5415:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5416:         $enddate = '.';
                   5417:     }
1.922     raeburn  5418:     my $rolelist;
                   5419:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5420:         $rolelist = join('&',@{$roles});
1.922     raeburn  5421:     }
1.662     raeburn  5422:     my %personnel = ();
1.841     albertel 5423: 
                   5424:     my %servers = &get_servers($dom,'library');
                   5425:     foreach my $tryserver (keys(%servers)) {
                   5426: 	%{$personnel{$tryserver}}=();
                   5427: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5428: 					    &escape($startdate).':'.
                   5429: 					    &escape($enddate).':'.
                   5430: 					    &escape($rolelist), $tryserver))) {
                   5431: 	    my ($key,$value) = split(/\=/,$line,2);
                   5432: 	    if (($key) && ($value)) {
                   5433: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5434: 	    }
                   5435: 	}
1.662     raeburn  5436:     }
                   5437:     return %personnel;
                   5438: }
1.658     raeburn  5439: 
1.1172.2.89  raeburn  5440: sub get_active_domroles {
                   5441:     my ($dom,$roles) = @_;
                   5442:     return () unless (ref($roles) eq 'ARRAY');
                   5443:     my $now = time;
                   5444:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5445:     my %domroles;
                   5446:     foreach my $server (keys(%dompersonnel)) {
                   5447:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5448:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5449:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5450:         }
                   5451:     }
                   5452:     return %domroles;
                   5453: }
                   5454: 
1.1057    www      5455: # ----------------------------------------------------------- Interval timing 
1.149     www      5456: 
1.1153    www      5457: {
                   5458: # Caches needed for speedup of navmaps
                   5459: # We don't want to cache this for very long at all (5 seconds at most)
                   5460: # 
                   5461: # The user for whom we cache
                   5462: my $cachedkey='';
                   5463: # The cached times for this user
                   5464: my %cachedtimes=();
                   5465: # When this was last done
1.1172.2.66  raeburn  5466: my $cachedtime='';
1.1153    www      5467: 
                   5468: sub load_all_first_access {
1.1154    raeburn  5469:     my ($uname,$udom)=@_;
1.1156    www      5470:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5471:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5472:         return;
                   5473:     }
                   5474:     $cachedtime=time;
                   5475:     $cachedkey=$uname.':'.$udom;
                   5476:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5477: }
                   5478: 
1.504     albertel 5479: sub get_first_access {
1.1162    raeburn  5480:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5481:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5482:     if ($argsymb) { $symb=$argsymb; }
                   5483:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5484:     if ($argmap) { $map = $argmap; }
1.926     albertel 5485:     if ($type eq 'course') {
                   5486: 	$res='course';
                   5487:     } elsif ($type eq 'map') {
1.588     albertel 5488: 	$res=&symbread($map);
                   5489:     } else {
                   5490: 	$res=$symb;
                   5491:     }
1.1153    www      5492:     &load_all_first_access($uname,$udom);
                   5493:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5494: }
                   5495: 
                   5496: sub set_first_access {
1.1162    raeburn  5497:     my ($type,$interval)=@_;
1.790     albertel 5498:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5499:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5500:     if ($type eq 'course') {
                   5501: 	$res='course';
                   5502:     } elsif ($type eq 'map') {
1.588     albertel 5503: 	$res=&symbread($map);
                   5504:     } else {
                   5505: 	$res=$symb;
                   5506:     }
1.1153    www      5507:     $cachedkey='';
1.1162    raeburn  5508:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5509:     if ($firstaccess) {
                   5510:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5511:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5512:                  "in $courseid");
                   5513:         return 'already_set';
                   5514:     } else {
1.1162    raeburn  5515:         my $start = time;
                   5516: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5517:                           $udom,$uname);
                   5518:         if ($putres eq 'ok') {
                   5519:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5520:                  $udom,$uname); 
                   5521:             &appenv(
                   5522:                      {
                   5523:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5524:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5525:                      }
                   5526:                   );
1.1172.2.97  raeburn  5527:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5528:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5529:             }
1.1172.2.102  raeburn  5530:         } elsif ($putres ne 'refused') {
                   5531:             &logthis("Result: $putres when attempting to set first access time ".
                   5532:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5533:         }
                   5534:         return $putres;
1.505     albertel 5535:     }
                   5536:     return 'already_set';
1.504     albertel 5537: }
1.1153    www      5538: }
1.1172.2.32  raeburn  5539: 
                   5540: sub checkout {
                   5541:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5542:     my $now=time;
                   5543:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5544:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5545:     my $infostr=&escape(
                   5546:                  'CHECKOUTTOKEN&'.
                   5547:                  $tuname.'&'.
                   5548:                  $tudom.'&'.
                   5549:                  $tcrsid.'&'.
                   5550:                  $symb.'&'.
1.1172.2.134  raeburn  5551:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5552:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5553:     if ($token=~/^error\:/) {
                   5554:         &logthis("<font color=\"blue\">WARNING: ".
                   5555:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5556:                  "</font>");
                   5557:         return '';
                   5558:     }
                   5559: 
                   5560:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5561:     $token=~tr/a-z/A-Z/;
                   5562: 
                   5563:     my %infohash=('resource.0.outtoken' => $token,
                   5564:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5565:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5566: 
                   5567:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5568:        return '';
                   5569:     } else {
                   5570:         &logthis("<font color=\"blue\">WARNING: ".
                   5571:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5572:                  "</font>");
                   5573:     }
                   5574: 
                   5575:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5576:                          &escape('Checkout '.$infostr.' - '.
                   5577:                                                  $token)) ne 'ok') {
                   5578:         return '';
                   5579:     } else {
                   5580:         &logthis("<font color=\"blue\">WARNING: ".
                   5581:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5582:                  "</font>");
                   5583:     }
                   5584:     return $token;
                   5585: }
                   5586: 
                   5587: # ------------------------------------------------------------ Check in an item
                   5588: 
                   5589: sub checkin {
                   5590:     my $token=shift;
                   5591:     my $now=time;
                   5592:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5593:     $lonhost=~tr/A-Z/a-z/;
                   5594:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5595:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5596:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5597:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5598:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5599: 
                   5600:     unless (($tuname) && ($tudom)) {
                   5601:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5602:         return '';
                   5603:     }
                   5604: 
                   5605:     unless (&allowed('mgr',$tcrsid)) {
                   5606:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5607:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5608:         return '';
                   5609:     }
                   5610: 
                   5611:     my %infohash=('resource.0.intoken' => $token,
                   5612:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5613:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5614: 
                   5615:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5616:        return '';
                   5617:     }
                   5618: 
                   5619:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5620:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5621:         return '';
                   5622:     }
                   5623: 
                   5624:     return ($symb,$tuname,$tudom,$tcrsid);
                   5625: }
                   5626: 
1.110     www      5627: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5628: 
                   5629: sub expirespread {
                   5630:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5631:     my $cid=$env{'request.course.id'}; 
1.110     www      5632:     if ($cid) {
                   5633:        my $now=time;
                   5634:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5635:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5636:                             $env{'course.'.$cid.'.num'}.
1.110     www      5637: 	        	    ':nohist_expirationdates:'.
                   5638:                             &escape($key).'='.$now,
1.620     albertel 5639:                             $env{'course.'.$cid.'.home'})
1.110     www      5640:     }
                   5641:     return 'ok';
1.14      www      5642: }
                   5643: 
1.109     www      5644: # ----------------------------------------------------- Devalidate Spreadsheets
                   5645: 
                   5646: sub devalidate {
1.325     www      5647:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5648:     my $cid=$env{'request.course.id'}; 
1.109     www      5649:     if ($cid) {
1.391     matthew  5650:         # delete the stored spreadsheets for
                   5651:         # - the student level sheet of this user in course's homespace
                   5652:         # - the assessment level sheet for this resource 
                   5653:         #   for this user in user's homespace
1.553     albertel 5654: 	# - current conditional state info
1.325     www      5655: 	my $key=$uname.':'.$udom.':';
1.109     www      5656:         my $status=
1.299     matthew  5657: 	    &del('nohist_calculatedsheets',
1.391     matthew  5658: 		 [$key.'studentcalc:'],
1.620     albertel 5659: 		 $env{'course.'.$cid.'.domain'},
                   5660: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5661: 		.' '.
                   5662: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5663: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5664:         unless ($status eq 'ok ok') {
                   5665:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5666:                     $uname.' at '.$udom.' for '.
1.109     www      5667: 		    $symb.': '.$status);
1.133     albertel 5668:         }
1.553     albertel 5669: 	&delenv('user.state.'.$cid);
1.109     www      5670:     }
                   5671: }
                   5672: 
1.265     albertel 5673: sub get_scalar {
                   5674:     my ($string,$end) = @_;
                   5675:     my $value;
                   5676:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5677: 	$value = $1;
                   5678:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5679: 	$value = $1;
                   5680:     }
                   5681:     return &unescape($value);
                   5682: }
                   5683: 
                   5684: sub array2str {
                   5685:   my (@array) = @_;
                   5686:   my $result=&arrayref2str(\@array);
                   5687:   $result=~s/^__ARRAY_REF__//;
                   5688:   $result=~s/__END_ARRAY_REF__$//;
                   5689:   return $result;
                   5690: }
                   5691: 
1.204     albertel 5692: sub arrayref2str {
                   5693:   my ($arrayref) = @_;
1.265     albertel 5694:   my $result='__ARRAY_REF__';
1.204     albertel 5695:   foreach my $elem (@$arrayref) {
1.265     albertel 5696:     if(ref($elem) eq 'ARRAY') {
                   5697:       $result.=&arrayref2str($elem).'&';
                   5698:     } elsif(ref($elem) eq 'HASH') {
                   5699:       $result.=&hashref2str($elem).'&';
                   5700:     } elsif(ref($elem)) {
                   5701:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5702:     } else {
                   5703:       $result.=&escape($elem).'&';
                   5704:     }
                   5705:   }
                   5706:   $result=~s/\&$//;
1.265     albertel 5707:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5708:   return $result;
                   5709: }
                   5710: 
1.168     albertel 5711: sub hash2str {
1.204     albertel 5712:   my (%hash) = @_;
                   5713:   my $result=&hashref2str(\%hash);
1.265     albertel 5714:   $result=~s/^__HASH_REF__//;
                   5715:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5716:   return $result;
                   5717: }
                   5718: 
                   5719: sub hashref2str {
                   5720:   my ($hashref)=@_;
1.265     albertel 5721:   my $result='__HASH_REF__';
1.800     albertel 5722:   foreach my $key (sort(keys(%$hashref))) {
                   5723:     if (ref($key) eq 'ARRAY') {
                   5724:       $result.=&arrayref2str($key).'=';
                   5725:     } elsif (ref($key) eq 'HASH') {
                   5726:       $result.=&hashref2str($key).'=';
                   5727:     } elsif (ref($key)) {
1.265     albertel 5728:       $result.='=';
1.800     albertel 5729:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5730:     } else {
1.1132    raeburn  5731: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5732:     }
                   5733: 
1.800     albertel 5734:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5735:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5736:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5737:       $result.=&hashref2str($hashref->{$key}).'&';
                   5738:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5739:        $result.='&';
1.800     albertel 5740:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5741:     } else {
1.800     albertel 5742:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5743:     }
                   5744:   }
1.168     albertel 5745:   $result=~s/\&$//;
1.265     albertel 5746:   $result .= '__END_HASH_REF__';
1.168     albertel 5747:   return $result;
                   5748: }
                   5749: 
                   5750: sub str2hash {
1.265     albertel 5751:     my ($string)=@_;
                   5752:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5753:     return %$hash;
                   5754: }
                   5755: 
                   5756: sub str2hashref {
1.168     albertel 5757:   my ($string) = @_;
1.265     albertel 5758: 
                   5759:   my %hash;
                   5760: 
                   5761:   if($string !~ /^__HASH_REF__/) {
                   5762:       if (! ($string eq '' || !defined($string))) {
                   5763: 	  $hash{'error'}='Not hash reference';
                   5764:       }
                   5765:       return (\%hash, $string);
                   5766:   }
                   5767: 
                   5768:   $string =~ s/^__HASH_REF__//;
                   5769: 
                   5770:   while($string !~ /^__END_HASH_REF__/) {
                   5771:       #key
                   5772:       my $key='';
                   5773:       if($string =~ /^__HASH_REF__/) {
                   5774:           ($key, $string)=&str2hashref($string);
                   5775:           if(defined($key->{'error'})) {
                   5776:               $hash{'error'}='Bad data';
                   5777:               return (\%hash, $string);
                   5778:           }
                   5779:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5780:           ($key, $string)=&str2arrayref($string);
                   5781:           if($key->[0] eq 'Array reference error') {
                   5782:               $hash{'error'}='Bad data';
                   5783:               return (\%hash, $string);
                   5784:           }
                   5785:       } else {
                   5786:           $string =~ s/^(.*?)=//;
1.267     albertel 5787: 	  $key=&unescape($1);
1.265     albertel 5788:       }
                   5789:       $string =~ s/^=//;
                   5790: 
                   5791:       #value
                   5792:       my $value='';
                   5793:       if($string =~ /^__HASH_REF__/) {
                   5794:           ($value, $string)=&str2hashref($string);
                   5795:           if(defined($value->{'error'})) {
                   5796:               $hash{'error'}='Bad data';
                   5797:               return (\%hash, $string);
                   5798:           }
                   5799:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5800:           ($value, $string)=&str2arrayref($string);
                   5801:           if($value->[0] eq 'Array reference error') {
                   5802:               $hash{'error'}='Bad data';
                   5803:               return (\%hash, $string);
                   5804:           }
                   5805:       } else {
                   5806: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5807:       }
                   5808:       $string =~ s/^&//;
                   5809: 
                   5810:       $hash{$key}=$value;
1.204     albertel 5811:   }
1.265     albertel 5812: 
                   5813:   $string =~ s/^__END_HASH_REF__//;
                   5814: 
                   5815:   return (\%hash, $string);
1.204     albertel 5816: }
                   5817: 
                   5818: sub str2array {
1.265     albertel 5819:     my ($string)=@_;
                   5820:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5821:     return @$array;
                   5822: }
                   5823: 
                   5824: sub str2arrayref {
1.204     albertel 5825:   my ($string) = @_;
1.265     albertel 5826:   my @array;
                   5827: 
                   5828:   if($string !~ /^__ARRAY_REF__/) {
                   5829:       if (! ($string eq '' || !defined($string))) {
                   5830: 	  $array[0]='Array reference error';
                   5831:       }
                   5832:       return (\@array, $string);
                   5833:   }
                   5834: 
                   5835:   $string =~ s/^__ARRAY_REF__//;
                   5836: 
                   5837:   while($string !~ /^__END_ARRAY_REF__/) {
                   5838:       my $value='';
                   5839:       if($string =~ /^__HASH_REF__/) {
                   5840:           ($value, $string)=&str2hashref($string);
                   5841:           if(defined($value->{'error'})) {
                   5842:               $array[0] ='Array reference error';
                   5843:               return (\@array, $string);
                   5844:           }
                   5845:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5846:           ($value, $string)=&str2arrayref($string);
                   5847:           if($value->[0] eq 'Array reference error') {
                   5848:               $array[0] ='Array reference error';
                   5849:               return (\@array, $string);
                   5850:           }
                   5851:       } else {
                   5852: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5853:       }
                   5854:       $string =~ s/^&//;
                   5855: 
                   5856:       push(@array, $value);
1.191     harris41 5857:   }
1.265     albertel 5858: 
                   5859:   $string =~ s/^__END_ARRAY_REF__//;
                   5860: 
                   5861:   return (\@array, $string);
1.168     albertel 5862: }
                   5863: 
1.167     albertel 5864: # -------------------------------------------------------------------Temp Store
                   5865: 
1.168     albertel 5866: sub tmpreset {
                   5867:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5868:   if (!$symb) {
                   5869:     $symb=&symbread();
1.620     albertel 5870:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5871:   }
                   5872:   $symb=escape($symb);
                   5873: 
1.620     albertel 5874:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5875:   $namespace=~s/\//\_/g;
                   5876:   $namespace=~s/\W//g;
                   5877: 
1.620     albertel 5878:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5879:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5880:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5881:       $stuname=&get_requestor_ip();
1.591     albertel 5882:   }
1.1117    foxr     5883:   my $path=LONCAPA::tempdir();
1.168     albertel 5884:   my %hash;
                   5885:   if (tie(%hash,'GDBM_File',
                   5886: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5887: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5888:     foreach my $key (keys(%hash)) {
1.180     albertel 5889:       if ($key=~ /:$symb/) {
1.168     albertel 5890: 	delete($hash{$key});
                   5891:       }
                   5892:     }
                   5893:   }
                   5894: }
                   5895: 
1.167     albertel 5896: sub tmpstore {
1.168     albertel 5897:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5898: 
                   5899:   if (!$symb) {
                   5900:     $symb=&symbread();
1.620     albertel 5901:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5902:   }
                   5903:   $symb=escape($symb);
                   5904: 
                   5905:   if (!$namespace) {
                   5906:     # I don't think we would ever want to store this for a course.
                   5907:     # it seems this will only be used if we don't have a course.
1.620     albertel 5908:     #$namespace=$env{'request.course.id'};
1.168     albertel 5909:     #if (!$namespace) {
1.620     albertel 5910:       $namespace=$env{'request.state'};
1.168     albertel 5911:     #}
                   5912:   }
                   5913:   $namespace=~s/\//\_/g;
                   5914:   $namespace=~s/\W//g;
1.620     albertel 5915:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5916:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5917:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5918:       $stuname=&get_requestor_ip();
1.591     albertel 5919:   }
1.168     albertel 5920:   my $now=time;
                   5921:   my %hash;
1.1117    foxr     5922:   my $path=LONCAPA::tempdir();
1.168     albertel 5923:   if (tie(%hash,'GDBM_File',
                   5924: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5925: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5926:     $hash{"version:$symb"}++;
                   5927:     my $version=$hash{"version:$symb"};
                   5928:     my $allkeys=''; 
                   5929:     foreach my $key (keys(%$storehash)) {
                   5930:       $allkeys.=$key.':';
1.591     albertel 5931:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5932:     }
                   5933:     $hash{"$version:$symb:timestamp"}=$now;
                   5934:     $allkeys.='timestamp';
                   5935:     $hash{"$version:keys:$symb"}=$allkeys;
                   5936:     if (untie(%hash)) {
                   5937:       return 'ok';
                   5938:     } else {
                   5939:       return "error:$!";
                   5940:     }
                   5941:   } else {
                   5942:     return "error:$!";
                   5943:   }
                   5944: }
1.167     albertel 5945: 
1.168     albertel 5946: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5947: 
1.168     albertel 5948: sub tmprestore {
                   5949:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5950: 
1.168     albertel 5951:   if (!$symb) {
                   5952:     $symb=&symbread();
1.620     albertel 5953:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5954:   }
                   5955:   $symb=escape($symb);
                   5956: 
1.620     albertel 5957:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5958: 
1.620     albertel 5959:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5960:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5961:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5962:       $stuname=&get_requestor_ip();
1.591     albertel 5963:   }
1.168     albertel 5964:   my %returnhash;
                   5965:   $namespace=~s/\//\_/g;
                   5966:   $namespace=~s/\W//g;
                   5967:   my %hash;
1.1117    foxr     5968:   my $path=LONCAPA::tempdir();
1.168     albertel 5969:   if (tie(%hash,'GDBM_File',
                   5970: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5971: 	  &GDBM_READER(),0640)) {
1.168     albertel 5972:     my $version=$hash{"version:$symb"};
                   5973:     $returnhash{'version'}=$version;
                   5974:     my $scope;
                   5975:     for ($scope=1;$scope<=$version;$scope++) {
                   5976:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5977:       my @keys=split(/:/,$vkeys);
                   5978:       my $key;
                   5979:       $returnhash{"$scope:keys"}=$vkeys;
                   5980:       foreach $key (@keys) {
1.591     albertel 5981: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5982: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5983:       }
                   5984:     }
1.168     albertel 5985:     if (!(untie(%hash))) {
                   5986:       return "error:$!";
                   5987:     }
                   5988:   } else {
                   5989:     return "error:$!";
                   5990:   }
                   5991:   return %returnhash;
1.167     albertel 5992: }
                   5993: 
1.9       www      5994: # ----------------------------------------------------------------------- Store
                   5995: 
                   5996: sub store {
1.1172.2.64  raeburn  5997:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5998:     my $home='';
                   5999: 
1.168     albertel 6000:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6001: 
1.213     www      6002:     $symb=&symbclean($symb);
1.122     albertel 6003:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6004: 
1.620     albertel 6005:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6006:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6007: 
                   6008:     &devalidate($symb,$stuname,$domain);
1.109     www      6009: 
                   6010:     $symb=escape($symb);
1.187     www      6011:     if (!$namespace) { 
1.620     albertel 6012:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6013:           return ''; 
                   6014:        } 
                   6015:     }
1.620     albertel 6016:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6017: 
1.1172.2.138  raeburn  6018:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6019:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6020: 
1.12      www      6021:     my $namevalue='';
1.800     albertel 6022:     foreach my $key (keys(%$storehash)) {
                   6023:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6024:     }
1.12      www      6025:     $namevalue=~s/\&$//;
1.187     www      6026:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6027:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6028: }
                   6029: 
1.47      www      6030: # -------------------------------------------------------------- Critical Store
                   6031: 
                   6032: sub cstore {
1.1172.2.64  raeburn  6033:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6034:     my $home='';
                   6035: 
1.168     albertel 6036:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6037: 
1.213     www      6038:     $symb=&symbclean($symb);
1.122     albertel 6039:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6040: 
1.620     albertel 6041:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6042:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6043: 
                   6044:     &devalidate($symb,$stuname,$domain);
1.109     www      6045: 
                   6046:     $symb=escape($symb);
1.187     www      6047:     if (!$namespace) { 
1.620     albertel 6048:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6049:           return ''; 
                   6050:        } 
                   6051:     }
1.620     albertel 6052:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6053: 
1.1172.2.138  raeburn  6054:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6055:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6056: 
1.47      www      6057:     my $namevalue='';
1.800     albertel 6058:     foreach my $key (keys(%$storehash)) {
                   6059:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6060:     }
1.47      www      6061:     $namevalue=~s/\&$//;
1.187     www      6062:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6063:     return critical
1.1172.2.64  raeburn  6064:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6065: }
                   6066: 
1.9       www      6067: # --------------------------------------------------------------------- Restore
                   6068: 
                   6069: sub restore {
1.124     www      6070:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6071:     my $home='';
                   6072: 
1.168     albertel 6073:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6074: 
1.122     albertel 6075:     if (!$symb) {
1.1172.2.26  raeburn  6076:         return if ($namespace eq 'courserequests');
                   6077:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6078:     } else {
1.1172.2.26  raeburn  6079:         unless ($namespace eq 'courserequests') {
                   6080:             $symb=&escape(&symbclean($symb));
                   6081:         }
1.122     albertel 6082:     }
1.188     www      6083:     if (!$namespace) { 
1.620     albertel 6084:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6085:           return ''; 
                   6086:        } 
                   6087:     }
1.620     albertel 6088:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6089:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6090:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6091:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6092: 
1.12      www      6093:     my %returnhash=();
1.800     albertel 6094:     foreach my $line (split(/\&/,$answer)) {
                   6095: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6096:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6097:     }
1.75      www      6098:     my $version;
                   6099:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6100:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6101:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6102:        }
1.75      www      6103:     }
1.13      www      6104:     return %returnhash;
1.34      www      6105: }
                   6106: 
                   6107: # ---------------------------------------------------------- Course Description
1.1118    foxr     6108: #
                   6109: #  
1.34      www      6110: 
                   6111: sub coursedescription {
1.731     albertel 6112:     my ($courseid,$args)=@_;
1.34      www      6113:     $courseid=~s/^\///;
1.49      www      6114:     $courseid=~s/\_/\//g;
1.34      www      6115:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6116:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6117:     my $normalid=$cdomain.'_'.$cnum;
                   6118:     # need to always cache even if we get errors otherwise we keep 
                   6119:     # trying and trying and trying to get the course description.
                   6120:     my %envhash=();
                   6121:     my %returnhash=();
1.731     albertel 6122:     
                   6123:     my $expiretime=600;
                   6124:     if ($env{'request.course.id'} eq $normalid) {
                   6125: 	$expiretime=120;
                   6126:     }
                   6127: 
                   6128:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6129:     if (!$args->{'freshen_cache'}
                   6130: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6131: 	foreach my $key (keys(%env)) {
                   6132: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6133: 	    my ($setting) = $1;
                   6134: 	    $returnhash{$setting} = $env{$key};
                   6135: 	}
                   6136: 	return %returnhash;
                   6137:     }
                   6138: 
1.1118    foxr     6139:     # get the data again
                   6140: 
1.731     albertel 6141:     if (!$args->{'one_time'}) {
                   6142: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6143:     }
1.811     albertel 6144: 
1.34      www      6145:     if ($chome ne 'no_host') {
1.302     albertel 6146:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6147:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6148: 	   my $username = $env{'user.name'}; # Defult username
                   6149: 	   if(defined $args->{'user'}) {
                   6150: 	       $username = $args->{'user'};
                   6151: 	   }
1.129     albertel 6152:            $returnhash{'home'}= $chome;
                   6153: 	   $returnhash{'domain'} = $cdomain;
                   6154: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6155:            if (!defined($returnhash{'type'})) {
                   6156:                $returnhash{'type'} = 'Course';
                   6157:            }
1.130     albertel 6158:            while (my ($name,$value) = each %returnhash) {
1.53      www      6159:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6160:            }
1.270     www      6161:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6162:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6163: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6164:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6165:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6166:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6167:        }
                   6168:     }
1.731     albertel 6169:     if (!$args->{'one_time'}) {
1.949     raeburn  6170: 	&appenv(\%envhash);
1.731     albertel 6171:     }
1.302     albertel 6172:     return %returnhash;
1.461     www      6173: }
                   6174: 
1.1080    raeburn  6175: sub update_released_required {
                   6176:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6177:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6178:         $cid = $env{'request.course.id'};
                   6179:         $cdom = $env{'course.'.$cid.'.domain'};
                   6180:         $cnum = $env{'course.'.$cid.'.num'};
                   6181:         $chome = $env{'course.'.$cid.'.home'};
                   6182:     }
                   6183:     if ($needsrelease) {
                   6184:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6185:         my $needsupdate;
                   6186:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6187:             $needsupdate = 1;
                   6188:         } else {
                   6189:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6190:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6191:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6192:                 $needsupdate = 1;
                   6193:             }
                   6194:         }
                   6195:         if ($needsupdate) {
                   6196:             my %needshash = (
                   6197:                              'internal.releaserequired' => $needsrelease,
                   6198:                             );
                   6199:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6200:             if ($putresult eq 'ok') {
                   6201:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6202:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6203:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6204:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6205:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6206:                 }
                   6207:             }
                   6208:         }
                   6209:     }
                   6210:     return;
                   6211: }
                   6212: 
1.461     www      6213: # -------------------------------------------------See if a user is privileged
                   6214: 
                   6215: sub privileged {
1.1172.2.23  raeburn  6216:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6217:     my $now = time;
1.1172.2.23  raeburn  6218:     my $roles;
                   6219:     if (ref($possroles) eq 'ARRAY') {
                   6220:         $roles = $possroles;
                   6221:     } else {
                   6222:         $roles = ['dc','su'];
                   6223:     }
                   6224:     if (ref($possdomains) eq 'ARRAY') {
                   6225:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6226:         foreach my $dom (@{$possdomains}) {
                   6227:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6228:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6229:                 foreach my $role (@{$roles}) {
                   6230:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6231:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6232:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6233:                             return 1 unless (($end && $end < $now) ||
                   6234:                                              ($start && $start > $now));
                   6235:                         }
                   6236:                     }
                   6237:                 }
                   6238:             }
                   6239:         }
                   6240:     } else {
                   6241:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6242:         my $now = time;
1.1170    droeschl 6243: 
1.1172.2.58  raeburn  6244:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6245:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6246:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6247:                 return 1 unless ($tend && $tend < $now)
                   6248:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6249:             }
1.1172.2.23  raeburn  6250:         }
                   6251:     }
1.461     www      6252:     return 0;
1.9       www      6253: }
1.1       albertel 6254: 
1.1172.2.23  raeburn  6255: sub privileged_by_domain {
                   6256:     my ($domains,$roles) = @_;
                   6257:     my %privileged = ();
                   6258:     my $cachetime = 60*60*24;
                   6259:     my $now = time;
                   6260:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6261:         return %privileged;
                   6262:     }
                   6263:     foreach my $dom (@{$domains}) {
                   6264:         next if (ref($privileged{$dom}) eq 'HASH');
                   6265:         my $needroles;
                   6266:         foreach my $role (@{$roles}) {
                   6267:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6268:             if (defined($cached)) {
                   6269:                 if (ref($result) eq 'HASH') {
                   6270:                     $privileged{$dom}{$role} = $result;
                   6271:                 }
                   6272:             } else {
                   6273:                 $needroles = 1;
                   6274:             }
                   6275:         }
                   6276:         if ($needroles) {
                   6277:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6278:             $privileged{$dom} = {};
                   6279:             foreach my $server (keys(%dompersonnel)) {
                   6280:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6281:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6282:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6283:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6284:                         next if ($end && $end < $now);
                   6285:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6286:                             $dompersonnel{$server}{$item};
                   6287:                     }
                   6288:                 }
                   6289:             }
                   6290:             if (ref($privileged{$dom}) eq 'HASH') {
                   6291:                 foreach my $role (@{$roles}) {
                   6292:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6293:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6294:                     } else {
                   6295:                         my %hash = ();
                   6296:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6297:                     }
                   6298:                 }
                   6299:             }
                   6300:         }
                   6301:     }
                   6302:     return %privileged;
                   6303: }
                   6304: 
1.103     harris41 6305: # -------------------------------------------------------- Get user privileges
1.11      www      6306: 
                   6307: sub rolesinit {
1.1169    droeschl 6308:     my ($domain, $username) = @_;
                   6309:     my %userroles = ('user.login.time' => time);
                   6310:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6311: 
                   6312:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6313:     # also, blocking can be triggered by an activating timer
                   6314:     # it's saved in the user's %env.
                   6315:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6316:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6317:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6318:         %timerintchk, %timerintenv);
                   6319: 
1.1162    raeburn  6320:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6321:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6322:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6323:     }
1.1169    droeschl 6324: 
1.1162    raeburn  6325:     foreach my $key (keys(%timerinterval)) {
                   6326:         my ($cid,$rest) = split(/\0/,$key);
                   6327:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6328:     }
1.1169    droeschl 6329: 
1.11      www      6330:     my %allroles=();
1.1162    raeburn  6331:     my %allgroups=();
1.11      www      6332: 
1.1172.2.58  raeburn  6333:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6334:         my $role = $rolesdump{$area};
                   6335:         $area =~ s/\_\w\w$//;
                   6336: 
                   6337:         my ($trole, $tend, $tstart, $group_privs);
                   6338: 
                   6339:         if ($role =~ /^cr/) {
                   6340:         # Custom role, defined by a user 
                   6341:         # e.g., user.role.cr/msu/smith/mynewrole
                   6342:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6343:                 $trole = $1;
                   6344:                 ($tend, $tstart) = split('_', $2);
                   6345:             } else {
                   6346:                 $trole = $role;
                   6347:             }
                   6348:         } elsif ($role =~ m|^gr/|) {
                   6349:         # Role of member in a group, defined within a course/community
                   6350:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6351:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6352:             next if $tstart eq '-1';
                   6353:             ($trole, $group_privs) = split(/\//, $trole);
                   6354:             $group_privs = &unescape($group_privs);
                   6355:         } else {
                   6356:         # Just a normal role, defined in roles.tab
                   6357:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6358:         }
                   6359: 
                   6360:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6361:                  $username);
                   6362:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6363: 
                   6364:         # role expired or not available yet?
                   6365:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6366:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6367: 
                   6368:         next if $area eq '' or $trole eq '';
                   6369: 
                   6370:         my $spec = "$trole.$area";
                   6371:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6372: 
                   6373:         if ($trole =~ /^cr\//) {
                   6374:         # Custom role, defined by a user
                   6375:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6376:         } elsif ($trole eq 'gr') {
                   6377:         # Role of a member in a group, defined within a course/community
                   6378:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6379:             next;
                   6380:         } else {
                   6381:         # Normal role, defined in roles.tab
                   6382:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6383:         }
                   6384: 
                   6385:         my $cid = $tdomain.'_'.$trest;
                   6386:         unless ($firstaccchk{$cid}) {
                   6387:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6388:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6389:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6390:                         $coursetimerstarts{$cid}{$item}; 
                   6391:                 }
                   6392:             }
                   6393:             $firstaccchk{$cid} = 1;
                   6394:         }
                   6395:         unless ($timerintchk{$cid}) {
                   6396:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6397:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6398:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6399:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6400:                 }
1.12      www      6401:             }
1.1169    droeschl 6402:             $timerintchk{$cid} = 1;
1.191     harris41 6403:         }
1.11      www      6404:     }
1.1169    droeschl 6405: 
1.1172.2.91  raeburn  6406:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6407:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6408:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6409:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6410: 
1.1162    raeburn  6411:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6412: }
                   6413: 
1.567     raeburn  6414: sub set_arearole {
1.1172.2.19  raeburn  6415:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6416:     unless ($nolog) {
1.567     raeburn  6417: # log the associated role with the area
1.1172.2.19  raeburn  6418:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6419:     }
1.743     albertel 6420:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6421: }
                   6422: 
                   6423: sub custom_roleprivs {
                   6424:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6425:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6426:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6427:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6428:         my ($rdummy,$roledef)=
                   6429:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6430:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6431:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6432:             if (defined($syspriv)) {
1.1043    raeburn  6433:                 if ($trest =~ /^$match_community$/) {
                   6434:                     $syspriv =~ s/bre\&S//; 
                   6435:                 }
1.567     raeburn  6436:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6437:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6438:             }
                   6439:             if ($tdomain ne '') {
                   6440:                 if (defined($dompriv)) {
                   6441:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6442:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6443:                 }
                   6444:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6445:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6446:                         my $rolename = $1;
                   6447:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6448:                     }
1.567     raeburn  6449:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6450:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6451:                 }
                   6452:             }
                   6453:         }
                   6454:     }
                   6455: }
                   6456: 
1.1172.2.89  raeburn  6457: sub course_adhocrole_privs {
                   6458:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6459:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6460:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6461:         my (%currprivs,%storeprivs);
                   6462:         foreach my $item (split(/:/,$coursepriv)) {
                   6463:             my ($priv,$restrict) = split(/\&/,$item);
                   6464:             $currprivs{$priv} = $restrict;
                   6465:         }
                   6466:         my (%possadd,%possremove,%full);
                   6467:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6468:             my ($priv,$restrict)=split(/\&/,$item);
                   6469:             $full{$priv} = $restrict;
                   6470:         }
                   6471:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6472:              next if ($item eq '');
                   6473:              my ($rule,$rest) = split(/=/,$item);
                   6474:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6475:              foreach my $priv (split(/:/,$rest)) {
                   6476:                  if ($priv ne '') {
                   6477:                      if ($rule eq 'off') {
                   6478:                          $possremove{$priv} = 1;
                   6479:                      } else {
                   6480:                          $possadd{$priv} = 1;
                   6481:                      }
                   6482:                  }
                   6483:              }
                   6484:          }
                   6485:          foreach my $priv (sort(keys(%full))) {
                   6486:              if (exists($currprivs{$priv})) {
                   6487:                  unless (exists($possremove{$priv})) {
                   6488:                      $storeprivs{$priv} = $currprivs{$priv};
                   6489:                  }
                   6490:              } elsif (exists($possadd{$priv})) {
                   6491:                  $storeprivs{$priv} = $full{$priv};
                   6492:              }
                   6493:          }
                   6494:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6495:      }
                   6496:      return $coursepriv;
                   6497: }
                   6498: 
1.678     raeburn  6499: sub group_roleprivs {
                   6500:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6501:     my $access = 1;
                   6502:     my $now = time;
                   6503:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6504:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6505:     if ($access) {
1.811     albertel 6506:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6507:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6508:     }
                   6509: }
1.567     raeburn  6510: 
                   6511: sub standard_roleprivs {
                   6512:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6513:     if (defined($pr{$trole.':s'})) {
                   6514:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6515:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6516:     }
                   6517:     if ($tdomain ne '') {
                   6518:         if (defined($pr{$trole.':d'})) {
                   6519:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6520:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6521:         }
                   6522:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6523:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6524:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6525:         }
                   6526:     }
                   6527: }
                   6528: 
                   6529: sub set_userprivs {
1.1064    raeburn  6530:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6531:     my $author=0;
                   6532:     my $adv=0;
1.1172.2.91  raeburn  6533:     my $rar=0;
1.678     raeburn  6534:     my %grouproles = ();
                   6535:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6536:         my @groupkeys; 
1.1000    raeburn  6537:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6538:             push(@groupkeys,$role);
                   6539:         }
                   6540:         if (ref($groups_roles) eq 'HASH') {
                   6541:             foreach my $key (keys(%{$groups_roles})) {
                   6542:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6543:                     push(@groupkeys,$key);
                   6544:                 }
                   6545:             }
                   6546:         }
                   6547:         if (@groupkeys > 0) {
                   6548:             foreach my $role (@groupkeys) {
                   6549:                 my ($trole,$area,$sec,$extendedarea);
                   6550:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6551:                     $trole = $1;
                   6552:                     $area = $2;
                   6553:                     $sec = $3;
                   6554:                     $extendedarea = $area.$sec;
                   6555:                     if (exists($$allgroups{$area})) {
                   6556:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6557:                             my $spec = $trole.'.'.$extendedarea;
                   6558:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6559:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6560:                         }
1.678     raeburn  6561:                     }
                   6562:                 }
                   6563:             }
                   6564:         }
                   6565:     }
1.800     albertel 6566:     foreach my $group (keys(%grouproles)) {
                   6567:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6568:     }
1.800     albertel 6569:     foreach my $role (keys(%{$allroles})) {
                   6570:         my %thesepriv;
1.941     raeburn  6571:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6572:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6573:             if ($item ne '') {
                   6574:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6575:                 if ($restrictions eq '') {
                   6576:                     $thesepriv{$privilege}='F';
                   6577:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6578:                     $thesepriv{$privilege}.=$restrictions;
                   6579:                 }
                   6580:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6581:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6582:             }
                   6583:         }
                   6584:         my $thesestr='';
1.1104    raeburn  6585:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6586: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6587: 	}
                   6588:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6589:     }
1.1172.2.91  raeburn  6590:     return ($author,$adv,$rar);
1.567     raeburn  6591: }
                   6592: 
1.994     raeburn  6593: sub role_status {
1.1104    raeburn  6594:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6595:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6596:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6597:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6598:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6599:             $$where = '/'.$two;
1.994     raeburn  6600:             $$trolecode=$$role.'.'.$$where;
                   6601:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6602:             $$tstatus='is';
1.1104    raeburn  6603:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6604:                 $$tstatus='future';
1.1034    raeburn  6605:                 if ($$tstart<$now) {
                   6606:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6607:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6608:                             my (%allroles,%allgroups,$group_privs,
                   6609:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6610:                             my %userroles = (
                   6611:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6612:                             );
1.1064    raeburn  6613:                             @rolecodes = ('cm'); 
1.1002    raeburn  6614:                             my $spec=$$role.'.'.$$where;
                   6615:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6616:                             if ($$role =~ /^cr\//) {
                   6617:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6618:                                 push(@rolecodes,'cr');
1.1002    raeburn  6619:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6620:                                 push(@rolecodes,$$role);
1.1002    raeburn  6621:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6622:                                                     $env{'user.name'});
1.1064    raeburn  6623:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6624:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6625:                                 $group_privs = &unescape($group_privs);
                   6626:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6627:                                 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  6628:                                 &get_groups_roles($tdomain,$trest,
                   6629:                                                   \%course_roles,\@rolecodes,
                   6630:                                                   \%groups_roles);
1.1002    raeburn  6631:                             } else {
1.1064    raeburn  6632:                                 push(@rolecodes,$$role);
1.1002    raeburn  6633:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6634:                             }
1.1172.2.91  raeburn  6635:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6636:                                                                    \%groups_roles);
1.1064    raeburn  6637:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6638:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6639:                         }
                   6640:                     }
1.1034    raeburn  6641:                     $$tstatus = 'is';
1.1002    raeburn  6642:                 }
1.994     raeburn  6643:             }
                   6644:             if ($$tend) {
1.1104    raeburn  6645:                 if ($$tend<$update) {
1.994     raeburn  6646:                     $$tstatus='expired';
                   6647:                 } elsif ($$tend<$now) {
                   6648:                     $$tstatus='will_not';
                   6649:                 }
                   6650:             }
                   6651:         }
                   6652:     }
                   6653: }
                   6654: 
1.1104    raeburn  6655: sub get_groups_roles {
                   6656:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6657:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6658:                   (ref($rolecodes) eq 'ARRAY') && 
                   6659:                   (ref($groups_roles) eq 'HASH')); 
                   6660:     if (keys(%{$cdom_courseroles}) > 0) {
                   6661:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6662:         if ($cdom ne '' && $cnum ne '') {
                   6663:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6664:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6665:                     my $crsrole = $1;
                   6666:                     my $crssec = $2;
                   6667:                     if ($crsrole =~ /^cr/) {
                   6668:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6669:                             push(@{$rolecodes},'cr');
                   6670:                         }
                   6671:                     } else {
                   6672:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6673:                             push(@{$rolecodes},$crsrole);
                   6674:                         }
                   6675:                     }
                   6676:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6677:                     if ($crssec ne '') {
                   6678:                         $rolekey .= "/$crssec";
                   6679:                     }
                   6680:                     $rolekey .= './';
                   6681:                     $groups_roles->{$rolekey} = $rolecodes;
                   6682:                 }
                   6683:             }
                   6684:         }
                   6685:     }
                   6686:     return;
                   6687: }
                   6688: 
                   6689: sub delete_env_groupprivs {
                   6690:     my ($where,$courseroles,$possroles) = @_;
                   6691:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6692:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6693:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6694:         %{$courseroles->{$udom}} =
                   6695:             &get_my_roles('','','userroles',['active'],
                   6696:                           $possroles,[$udom],1);
                   6697:     }
                   6698:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6699:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6700:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6701:             my $area = '/'.$cdom.'/'.$cnum;
                   6702:             my $privkey = "user.priv.$crsrole.$area";
                   6703:             if ($crssec ne '') {
                   6704:                 $privkey .= '/'.$crssec;
                   6705:             }
                   6706:             $privkey .= ".$area/$group";
                   6707:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6708:         }
                   6709:     }
                   6710:     return;
                   6711: }
                   6712: 
1.994     raeburn  6713: sub check_adhoc_privs {
1.1172.2.86  raeburn  6714:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6715:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6716:     if ($sec) {
                   6717:         $cckey .= '/'.$sec;
                   6718:     }
1.1172.2.9  raeburn  6719:     my $setprivs;
1.994     raeburn  6720:     if ($env{$cckey}) {
                   6721:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6722:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6723:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6724:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6725:             $setprivs = 1;
1.994     raeburn  6726:         }
                   6727:     } else {
1.1172.2.87  raeburn  6728:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6729:         $setprivs = 1;
1.994     raeburn  6730:     }
1.1172.2.9  raeburn  6731:     return $setprivs;
1.994     raeburn  6732: }
                   6733: 
                   6734: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6735: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6736:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6737:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6738:     if ($sec ne '') {
                   6739:         $area .= '/'.$sec;
                   6740:     }
1.994     raeburn  6741:     my $spec = $role.'.'.$area;
                   6742:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6743:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6744:     my %rolehash = ();
1.1172.2.89  raeburn  6745:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6746:         my $rolename = $1;
1.1172.2.84  raeburn  6747:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6748:         my %domdef = &get_domain_defaults($dcdom);
                   6749:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6750:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6751:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6752:             }
                   6753:         }
1.1172.2.84  raeburn  6754:     } else {
                   6755:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6756:     }
1.1172.2.91  raeburn  6757:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6758:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6759:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6760:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6761:         &appenv( {'request.role'        => $spec,
                   6762:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6763:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6764:                  }
                   6765:                );
                   6766:         my $tadv=0;
                   6767:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6768:         &appenv({'request.role.adv'    => $tadv});
                   6769:     }
1.994     raeburn  6770: }
                   6771: 
1.12      www      6772: # --------------------------------------------------------------- get interface
                   6773: 
                   6774: sub get {
1.131     albertel 6775:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6776:    my $items='';
1.800     albertel 6777:    foreach my $item (@$storearr) {
                   6778:        $items.=&escape($item).'&';
1.191     harris41 6779:    }
1.12      www      6780:    $items=~s/\&$//;
1.620     albertel 6781:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6782:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6783:    my $uhome=&homeserver($uname,$udomain);
                   6784: 
1.133     albertel 6785:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6786:    my @pairs=split(/\&/,$rep);
1.273     albertel 6787:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6788:      return @pairs;
                   6789:    }
1.15      www      6790:    my %returnhash=();
1.42      www      6791:    my $i=0;
1.800     albertel 6792:    foreach my $item (@$storearr) {
                   6793:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6794:       $i++;
1.191     harris41 6795:    }
1.15      www      6796:    return %returnhash;
1.27      www      6797: }
                   6798: 
                   6799: # --------------------------------------------------------------- del interface
                   6800: 
                   6801: sub del {
1.133     albertel 6802:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6803:    my $items='';
1.800     albertel 6804:    foreach my $item (@$storearr) {
                   6805:        $items.=&escape($item).'&';
1.191     harris41 6806:    }
1.984     neumanie 6807: 
1.27      www      6808:    $items=~s/\&$//;
1.620     albertel 6809:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6810:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6811:    my $uhome=&homeserver($uname,$udomain);
                   6812:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6813: }
                   6814: 
                   6815: # -------------------------------------------------------------- dump interface
                   6816: 
1.1172.2.22  raeburn  6817: sub unserialize {
                   6818:     my ($rep, $escapedkeys) = @_;
                   6819: 
                   6820:     return {} if $rep =~ /^error/;
                   6821: 
                   6822:     my %returnhash=();
                   6823:     foreach my $item (split(/\&/,$rep)) {
                   6824:         my ($key, $value) = split(/=/, $item, 2);
                   6825:         $key = unescape($key) unless $escapedkeys;
                   6826:         next if $key =~ /^error: 2 /;
                   6827:         $returnhash{$key} = &thaw_unescape($value);
                   6828:     }
                   6829:     return \%returnhash;
                   6830: }
                   6831: 
                   6832: # see Lond::dump_with_regexp
                   6833: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6834: sub dump {
1.1172.2.22  raeburn  6835:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6836:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6837:     if (!$uname) { $uname=$env{'user.name'}; }
                   6838:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6839: 
1.1172.2.55  raeburn  6840:     if ($regexp) {
                   6841:         $regexp=&escape($regexp);
                   6842:     } else {
                   6843:         $regexp='.';
                   6844:     }
1.1172.2.22  raeburn  6845:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6846:         # user is hosted on this machine
1.1172.2.55  raeburn  6847:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6848:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6849:         return %{&unserialize($reply, $escapedkeys)};
                   6850:     }
1.1166    raeburn  6851:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6852:     my @pairs=split(/\&/,$rep);
                   6853:     my %returnhash=();
1.1098    foxr     6854:     if (!($rep =~ /^error/ )) {
                   6855: 	foreach my $item (@pairs) {
                   6856: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6857:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6858: 	    next if ($key =~ /^error: 2 /);
                   6859: 	    $returnhash{$key}=&thaw_unescape($value);
                   6860: 	}
1.755     albertel 6861:     }
                   6862:     return %returnhash;
1.407     www      6863: }
                   6864: 
1.1098    foxr     6865: 
1.717     albertel 6866: # --------------------------------------------------------- dumpstore interface
                   6867: 
                   6868: sub dumpstore {
                   6869:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6870:    # same as dump but keys must be escaped. They may contain colon separated
                   6871:    # lists of values that may themself contain colons (e.g. symbs).
                   6872:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6873: }
                   6874: 
1.407     www      6875: # -------------------------------------------------------------- keys interface
                   6876: 
                   6877: sub getkeys {
                   6878:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6879:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6880:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6881:    my $uhome=&homeserver($uname,$udomain);
                   6882:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6883:    my @keyarray=();
1.800     albertel 6884:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6885:       next if ($key =~ /^error: 2 /);
1.800     albertel 6886:       push(@keyarray,&unescape($key));
1.407     www      6887:    }
                   6888:    return @keyarray;
1.318     matthew  6889: }
                   6890: 
1.319     matthew  6891: # --------------------------------------------------------------- currentdump
                   6892: sub currentdump {
1.328     matthew  6893:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6894:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6895:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6896:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6897:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6898:    my $rep;
                   6899: 
                   6900:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6901:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6902:                    $courseid)));
                   6903:    } else {
                   6904:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6905:    }
                   6906: 
1.318     matthew  6907:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6908:    #
1.318     matthew  6909:    my %returnhash=();
1.319     matthew  6910:    #
                   6911:    if ($rep eq "unknown_cmd") { 
                   6912:        # an old lond will not know currentdump
                   6913:        # Do a dump and make it look like a currentdump
1.822     albertel 6914:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6915:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6916:        my %hash = @tmp;
                   6917:        @tmp=();
1.424     matthew  6918:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6919:    } else {
                   6920:        my @pairs=split(/\&/,$rep);
1.800     albertel 6921:        foreach my $pair (@pairs) {
                   6922:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6923:            my ($symb,$param) = split(/:/,$key);
                   6924:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6925:                                                         &thaw_unescape($value);
1.319     matthew  6926:        }
1.191     harris41 6927:    }
1.12      www      6928:    return %returnhash;
1.424     matthew  6929: }
                   6930: 
                   6931: sub convert_dump_to_currentdump{
                   6932:     my %hash = %{shift()};
                   6933:     my %returnhash;
                   6934:     # Code ripped from lond, essentially.  The only difference
                   6935:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6936:     # we might run in to problems with parameter names =~ /^v\./
                   6937:     while (my ($key,$value) = each(%hash)) {
                   6938:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6939: 	$symb  = &unescape($symb);
                   6940: 	$param = &unescape($param);
1.424     matthew  6941:         next if ($v eq 'version' || $symb eq 'keys');
                   6942:         next if (exists($returnhash{$symb}) &&
                   6943:                  exists($returnhash{$symb}->{$param}) &&
                   6944:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6945:         $returnhash{$symb}->{$param}=$value;
                   6946:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6947:     }
                   6948:     #
                   6949:     # Remove all of the keys in the hashes which keep track of
                   6950:     # the version of the parameter.
                   6951:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6952:         # use a foreach because we are going to delete from the hash.
                   6953:         foreach my $key (keys(%$param_hash)) {
                   6954:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6955:         }
                   6956:     }
                   6957:     return \%returnhash;
1.12      www      6958: }
                   6959: 
1.627     albertel 6960: # ------------------------------------------------------ critical inc interface
                   6961: 
                   6962: sub cinc {
                   6963:     return &inc(@_,'critical');
                   6964: }
                   6965: 
1.449     matthew  6966: # --------------------------------------------------------------- inc interface
                   6967: 
                   6968: sub inc {
1.627     albertel 6969:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6970:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6971:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6972:     my $uhome=&homeserver($uname,$udomain);
                   6973:     my $items='';
                   6974:     if (! ref($store)) {
                   6975:         # got a single value, so use that instead
                   6976:         $items = &escape($store).'=&';
                   6977:     } elsif (ref($store) eq 'SCALAR') {
                   6978:         $items = &escape($$store).'=&';        
                   6979:     } elsif (ref($store) eq 'ARRAY') {
                   6980:         $items = join('=&',map {&escape($_);} @{$store});
                   6981:     } elsif (ref($store) eq 'HASH') {
                   6982:         while (my($key,$value) = each(%{$store})) {
                   6983:             $items.= &escape($key).'='.&escape($value).'&';
                   6984:         }
                   6985:     }
                   6986:     $items=~s/\&$//;
1.627     albertel 6987:     if ($critical) {
                   6988: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6989:     } else {
                   6990: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6991:     }
1.449     matthew  6992: }
                   6993: 
1.12      www      6994: # --------------------------------------------------------------- put interface
                   6995: 
                   6996: sub put {
1.134     albertel 6997:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6999:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7000:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7001:    my $items='';
1.800     albertel 7002:    foreach my $item (keys(%$storehash)) {
                   7003:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7004:    }
1.12      www      7005:    $items=~s/\&$//;
1.134     albertel 7006:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7007: }
                   7008: 
1.631     albertel 7009: # ------------------------------------------------------------ newput interface
                   7010: 
                   7011: sub newput {
                   7012:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7014:    if (!$uname) { $uname=$env{'user.name'}; }
                   7015:    my $uhome=&homeserver($uname,$udomain);
                   7016:    my $items='';
                   7017:    foreach my $key (keys(%$storehash)) {
                   7018:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7019:    }
                   7020:    $items=~s/\&$//;
                   7021:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7022: }
                   7023: 
                   7024: # ---------------------------------------------------------  putstore interface
                   7025: 
1.524     raeburn  7026: sub putstore {
1.1172.2.59  raeburn  7027:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7028:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7029:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7030:    my $uhome=&homeserver($uname,$udomain);
                   7031:    my $items='';
1.715     albertel 7032:    foreach my $key (keys(%$storehash)) {
                   7033:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7034:    }
1.715     albertel 7035:    $items=~s/\&$//;
1.716     albertel 7036:    my $esc_symb=&escape($symb);
                   7037:    my $esc_v=&escape($version);
1.715     albertel 7038:    my $reply =
1.716     albertel 7039:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7040: 	      $uhome);
1.1172.2.59  raeburn  7041:    if (($tolog) && ($reply eq 'ok')) {
                   7042:        my $namevalue='';
                   7043:        foreach my $key (keys(%{$storehash})) {
                   7044:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7045:        }
1.1172.2.134  raeburn  7046:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7047:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7048:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7049:                      '&version='.$esc_v.
                   7050:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7051:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7052:    }
1.715     albertel 7053:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7054:        # gfall back to way things use to be done
1.715     albertel 7055:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7056: 			    $uname);
1.524     raeburn  7057:    }
1.715     albertel 7058:    return $reply;
                   7059: }
                   7060: 
                   7061: sub old_putstore {
1.716     albertel 7062:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7063:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7064:     if (!$uname) { $uname=$env{'user.name'}; }
                   7065:     my $uhome=&homeserver($uname,$udomain);
                   7066:     my %newstorehash;
1.800     albertel 7067:     foreach my $item (keys(%$storehash)) {
                   7068: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7069: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7070:     }
                   7071:     my $items='';
                   7072:     my %allitems = ();
1.800     albertel 7073:     foreach my $item (keys(%newstorehash)) {
                   7074: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7075: 	    my $key = $1.':keys:'.$2;
                   7076: 	    $allitems{$key} .= $3.':';
                   7077: 	}
1.800     albertel 7078: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7079:     }
1.800     albertel 7080:     foreach my $item (keys(%allitems)) {
                   7081: 	$allitems{$item} =~ s/\:$//;
                   7082: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7083:     }
                   7084:     $items=~s/\&$//;
                   7085:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7086: }
                   7087: 
1.47      www      7088: # ------------------------------------------------------ critical put interface
                   7089: 
                   7090: sub cput {
1.134     albertel 7091:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7092:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7093:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7094:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7095:    my $items='';
1.800     albertel 7096:    foreach my $item (keys(%$storehash)) {
                   7097:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7098:    }
1.47      www      7099:    $items=~s/\&$//;
1.134     albertel 7100:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7101: }
                   7102: 
                   7103: # -------------------------------------------------------------- eget interface
                   7104: 
                   7105: sub eget {
1.133     albertel 7106:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7107:    my $items='';
1.800     albertel 7108:    foreach my $item (@$storearr) {
                   7109:        $items.=&escape($item).'&';
1.191     harris41 7110:    }
1.12      www      7111:    $items=~s/\&$//;
1.620     albertel 7112:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7113:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7114:    my $uhome=&homeserver($uname,$udomain);
                   7115:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7116:    my @pairs=split(/\&/,$rep);
                   7117:    my %returnhash=();
1.42      www      7118:    my $i=0;
1.800     albertel 7119:    foreach my $item (@$storearr) {
                   7120:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7121:       $i++;
1.191     harris41 7122:    }
1.12      www      7123:    return %returnhash;
                   7124: }
                   7125: 
1.667     albertel 7126: # ------------------------------------------------------------ tmpput interface
                   7127: sub tmpput {
1.802     raeburn  7128:     my ($storehash,$server,$context)=@_;
1.667     albertel 7129:     my $items='';
1.800     albertel 7130:     foreach my $item (keys(%$storehash)) {
                   7131: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7132:     }
                   7133:     $items=~s/\&$//;
1.802     raeburn  7134:     if (defined($context)) {
                   7135:         $items .= ':'.&escape($context);
                   7136:     }
1.667     albertel 7137:     return &reply("tmpput:$items",$server);
                   7138: }
                   7139: 
                   7140: # ------------------------------------------------------------ tmpget interface
                   7141: sub tmpget {
1.688     albertel 7142:     my ($token,$server)=@_;
                   7143:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7144:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7145:     my %returnhash;
1.1172.2.85  raeburn  7146:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7147:         return %returnhash;
                   7148:     }
1.667     albertel 7149:     foreach my $item (split(/\&/,$rep)) {
                   7150: 	my ($key,$value)=split(/=/,$item);
                   7151: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7152:     }
                   7153:     return %returnhash;
                   7154: }
                   7155: 
1.1113    raeburn  7156: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7157: sub tmpdel {
                   7158:     my ($token,$server)=@_;
                   7159:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7160:     return &reply("tmpdel:$token",$server);
                   7161: }
                   7162: 
1.1172.2.13  raeburn  7163: # ------------------------------------------------------------ get_timebased_id
                   7164: 
                   7165: sub get_timebased_id {
                   7166:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7167:         $maxtries) = @_;
                   7168:     my ($newid,$error,$dellock);
                   7169:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7170:         return ('','ok','invalid call to get suffix');
                   7171:     }
                   7172: 
                   7173: # set defaults for any optional args for which values were not supplied
                   7174:     if ($who eq '') {
                   7175:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7176:     }
                   7177:     if (!$locktries) {
                   7178:         $locktries = 3;
                   7179:     }
                   7180:     if (!$maxtries) {
                   7181:         $maxtries = 10;
                   7182:     }
                   7183: 
                   7184:     if (($cdom eq '') || ($cnum eq '')) {
                   7185:         if ($env{'request.course.id'}) {
                   7186:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7187:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7188:         }
                   7189:         if (($cdom eq '') || ($cnum eq '')) {
                   7190:             return ('','ok','call to get suffix not in course context');
                   7191:         }
                   7192:     }
                   7193: 
                   7194: # construct locking item
                   7195:     my $lockhash = {
                   7196:                       $prefix."\0".'locked_'.$keyid => $who,
                   7197:                    };
                   7198:     my $tries = 0;
                   7199: 
                   7200: # attempt to get lock on nohist_$namespace file
                   7201:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7202:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7203:         $tries ++;
                   7204:         sleep 1;
                   7205:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7206:     }
                   7207: 
                   7208: # attempt to get unique identifier, based on current timestamp
                   7209:     if ($gotlock eq 'ok') {
                   7210:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7211:         my $id = time;
                   7212:         $newid = $id;
1.1172.2.56  raeburn  7213:         if ($idtype eq 'addcode') {
                   7214:             $newid .= &sixnum_code();
                   7215:         }
1.1172.2.13  raeburn  7216:         my $idtries = 0;
                   7217:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7218:             if ($idtype eq 'concat') {
                   7219:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7220:             } elsif ($idtype eq 'addcode') {
                   7221:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7222:             } else {
                   7223:                 $newid ++;
                   7224:             }
                   7225:             $idtries ++;
                   7226:         }
                   7227:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7228:             my %new_item =  (
                   7229:                               $prefix."\0".$newid => $who,
                   7230:                             );
                   7231:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7232:                                                  $cdom,$cnum);
                   7233:             if ($putresult ne 'ok') {
                   7234:                 undef($newid);
                   7235:                 $error = 'error saving new item: '.$putresult;
                   7236:             }
                   7237:         } else {
1.1172.2.56  raeburn  7238:              undef($newid);
1.1172.2.13  raeburn  7239:              $error = ('error: no unique suffix available for the new item ');
                   7240:         }
                   7241: #  remove lock
                   7242:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7243:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7244:     } else {
                   7245:         $error = "error: could not obtain lockfile\n";
                   7246:         $dellock = 'ok';
1.1172.2.58  raeburn  7247:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7248:             $dellock = 'nolock';
                   7249:         }
1.1172.2.13  raeburn  7250:     }
                   7251:     return ($newid,$dellock,$error);
                   7252: }
                   7253: 
1.1172.2.56  raeburn  7254: sub sixnum_code {
                   7255:     my $code;
                   7256:     for (0..6) {
                   7257:         $code .= int( rand(9) );
                   7258:     }
                   7259:     return $code;
                   7260: }
                   7261: 
1.765     albertel 7262: # -------------------------------------------------- portfolio access checking
                   7263: 
                   7264: sub portfolio_access {
1.1172.2.77  raeburn  7265:     my ($requrl,$clientip) = @_;
1.765     albertel 7266:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7267:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7268:     if ($result) {
                   7269:         my %setters;
                   7270:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7271:             my ($startblock,$endblock) =
                   7272:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7273:             if ($startblock && $endblock) {
                   7274:                 return 'B';
                   7275:             }
                   7276:         } else {
                   7277:             my ($startblock,$endblock) =
                   7278:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7279:             if ($startblock && $endblock) {
                   7280:                 return 'B';
                   7281:             }
                   7282:         }
                   7283:     }
1.765     albertel 7284:     if ($result eq 'ok') {
1.766     albertel 7285:        return 'F';
1.765     albertel 7286:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7287:        return 'A';
1.765     albertel 7288:     }
1.766     albertel 7289:     return '';
1.765     albertel 7290: }
                   7291: 
                   7292: sub get_portfolio_access {
1.1172.2.77  raeburn  7293:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7294: 
                   7295:     if (!ref($access_hash)) {
                   7296: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7297: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7298: 						   $file_name);
                   7299: 	$access_hash = $access_controls{$file_name};
                   7300:     }
                   7301: 
1.1172.2.77  raeburn  7302:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7303:     my $now = time;
                   7304:     if (ref($access_hash) eq 'HASH') {
                   7305:         foreach my $key (keys(%{$access_hash})) {
                   7306:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7307:             if ($start > $now) {
                   7308:                 next;
                   7309:             }
                   7310:             if ($end && $end<$now) {
                   7311:                 next;
                   7312:             }
                   7313:             if ($scope eq 'public') {
                   7314:                 $public = $key;
                   7315:                 last;
                   7316:             } elsif ($scope eq 'guest') {
                   7317:                 $guest = $key;
                   7318:             } elsif ($scope eq 'domains') {
                   7319:                 push(@domains,$key);
                   7320:             } elsif ($scope eq 'users') {
                   7321:                 push(@users,$key);
                   7322:             } elsif ($scope eq 'course') {
                   7323:                 push(@courses,$key);
                   7324:             } elsif ($scope eq 'group') {
                   7325:                 push(@groups,$key);
1.1172.2.77  raeburn  7326:             } elsif ($scope eq 'ip') {
                   7327:                 push(@ips,$key);
1.765     albertel 7328:             }
                   7329:         }
                   7330:         if ($public) {
                   7331:             return 'ok';
1.1172.2.77  raeburn  7332:         } elsif (@ips > 0) {
                   7333:             my $allowed;
                   7334:             foreach my $ipkey (@ips) {
                   7335:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7336:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7337:                         $allowed = 1;
                   7338:                         last;
                   7339:                     }
                   7340:                 }
                   7341:             }
                   7342:             if ($allowed) {
                   7343:                 return 'ok';
                   7344:             }
1.765     albertel 7345:         }
                   7346:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7347:             if ($guest) {
                   7348:                 return $guest;
                   7349:             }
                   7350:         } else {
                   7351:             if (@domains > 0) {
                   7352:                 foreach my $domkey (@domains) {
                   7353:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7354:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7355:                             return 'ok';
                   7356:                         }
                   7357:                     }
                   7358:                 }
                   7359:             }
                   7360:             if (@users > 0) {
                   7361:                 foreach my $userkey (@users) {
1.865     raeburn  7362:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7363:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7364:                             if (ref($item) eq 'HASH') {
                   7365:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7366:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7367:                                     return 'ok';
                   7368:                                 }
                   7369:                             }
                   7370:                         }
                   7371:                     } 
1.765     albertel 7372:                 }
                   7373:             }
                   7374:             my %roleshash;
                   7375:             my @courses_and_groups = @courses;
                   7376:             push(@courses_and_groups,@groups); 
                   7377:             if (@courses_and_groups > 0) {
                   7378:                 my (%allgroups,%allroles); 
                   7379:                 my ($start,$end,$role,$sec,$group);
                   7380:                 foreach my $envkey (%env) {
1.1060    raeburn  7381:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7382:                         my $cid = $2.'_'.$3; 
                   7383:                         if ($1 eq 'gr') {
                   7384:                             $group = $4;
                   7385:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7386:                         } else {
                   7387:                             if ($4 eq '') {
                   7388:                                 $sec = 'none';
                   7389:                             } else {
                   7390:                                 $sec = $4;
                   7391:                             }
                   7392:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7393:                         }
1.811     albertel 7394:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7395:                         my $cid = $2.'_'.$3;
                   7396:                         if ($4 eq '') {
                   7397:                             $sec = 'none';
                   7398:                         } else {
                   7399:                             $sec = $4;
                   7400:                         }
                   7401:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7402:                     }
                   7403:                 }
                   7404:                 if (keys(%allroles) == 0) {
                   7405:                     return;
                   7406:                 }
                   7407:                 foreach my $key (@courses_and_groups) {
                   7408:                     my %content = %{$$access_hash{$key}};
                   7409:                     my $cnum = $content{'number'};
                   7410:                     my $cdom = $content{'domain'};
                   7411:                     my $cid = $cdom.'_'.$cnum;
                   7412:                     if (!exists($allroles{$cid})) {
                   7413:                         next;
                   7414:                     }    
                   7415:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7416:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7417:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7418:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7419:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7420:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7421:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7422:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7423:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7424:                                         if (grep/^all$/,@sections) {
                   7425:                                             return 'ok';
                   7426:                                         } else {
                   7427:                                             if (grep/^$sec$/,@sections) {
                   7428:                                                 return 'ok';
                   7429:                                             }
                   7430:                                         }
                   7431:                                     }
                   7432:                                 }
                   7433:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7434:                                     if (grep/^none$/,@groups) {
                   7435:                                         return 'ok';
                   7436:                                     }
                   7437:                                 } else {
                   7438:                                     if (grep/^all$/,@groups) {
                   7439:                                         return 'ok';
                   7440:                                     } 
                   7441:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7442:                                         if (grep/^$group$/,@groups) {
                   7443:                                             return 'ok';
                   7444:                                         }
                   7445:                                     }
                   7446:                                 } 
                   7447:                             }
                   7448:                         }
                   7449:                     }
                   7450:                 }
                   7451:             }
                   7452:             if ($guest) {
                   7453:                 return $guest;
                   7454:             }
                   7455:         }
                   7456:     }
                   7457:     return;
                   7458: }
                   7459: 
                   7460: sub course_group_datechecker {
                   7461:     my ($dates,$now,$status) = @_;
                   7462:     my ($start,$end) = split(/\./,$dates);
                   7463:     if (!$start && !$end) {
                   7464:         return 'ok';
                   7465:     }
                   7466:     if (grep/^active$/,@{$status}) {
                   7467:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7468:             return 'ok';
                   7469:         }
                   7470:     }
                   7471:     if (grep/^previous$/,@{$status}) {
                   7472:         if ($end > $now ) {
                   7473:             return 'ok';
                   7474:         }
                   7475:     }
                   7476:     if (grep/^future$/,@{$status}) {
                   7477:         if ($start > $now) {
                   7478:             return 'ok';
                   7479:         }
                   7480:     }
                   7481:     return; 
                   7482: }
                   7483: 
                   7484: sub parse_portfolio_url {
                   7485:     my ($url) = @_;
                   7486: 
                   7487:     my ($type,$udom,$unum,$group,$file_name);
                   7488:     
1.823     albertel 7489:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7490: 	$type = 1;
                   7491:         $udom = $1;
                   7492:         $unum = $2;
                   7493:         $file_name = $3;
1.823     albertel 7494:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7495: 	$type = 2;
                   7496:         $udom = $1;
                   7497:         $unum = $2;
                   7498:         $group = $3;
                   7499:         $file_name = $3.'/'.$4;
                   7500:     }
                   7501:     if (wantarray) {
                   7502: 	return ($type,$udom,$unum,$file_name,$group);
                   7503:     }
                   7504:     return $type;
                   7505: }
                   7506: 
                   7507: sub is_portfolio_url {
                   7508:     my ($url) = @_;
                   7509:     return scalar(&parse_portfolio_url($url));
                   7510: }
                   7511: 
1.798     raeburn  7512: sub is_portfolio_file {
                   7513:     my ($file) = @_;
1.820     raeburn  7514:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7515:         return 1;
                   7516:     }
                   7517:     return;
                   7518: }
                   7519: 
1.976     raeburn  7520: sub usertools_access {
1.1084    raeburn  7521:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7522:     my ($access,%tools);
                   7523:     if ($context eq '') {
                   7524:         $context = 'tools';
                   7525:     }
                   7526:     if ($context eq 'requestcourses') {
                   7527:         %tools = (
                   7528:                       official   => 1,
                   7529:                       unofficial => 1,
1.1006    raeburn  7530:                       community  => 1,
1.1172.2.37  raeburn  7531:                       textbook   => 1,
1.985     raeburn  7532:                  );
1.1172.2.9  raeburn  7533:     } elsif ($context eq 'requestauthor') {
                   7534:         %tools = (
                   7535:                       requestauthor => 1,
                   7536:                  );
1.985     raeburn  7537:     } else {
                   7538:         %tools = (
                   7539:                       aboutme   => 1,
                   7540:                       blog      => 1,
1.1172.2.6  raeburn  7541:                       webdav    => 1,
1.985     raeburn  7542:                       portfolio => 1,
                   7543:                  );
                   7544:     }
1.976     raeburn  7545:     return if (!defined($tools{$tool}));
                   7546: 
1.1172.2.35  raeburn  7547:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7548:         $udom = $env{'user.domain'};
                   7549:         $uname = $env{'user.name'};
                   7550:     }
                   7551: 
1.978     raeburn  7552:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7553:         if ($action ne 'reload') {
1.985     raeburn  7554:             if ($context eq 'requestcourses') {
                   7555:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7556:             } elsif ($context eq 'requestauthor') {
                   7557:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7558:             } else {
                   7559:                 return $env{'environment.availabletools.'.$tool};
                   7560:             }
                   7561:         }
1.976     raeburn  7562:     }
                   7563: 
1.1172.2.9  raeburn  7564:     my ($toolstatus,$inststatus,$envkey);
                   7565:     if ($context eq 'requestauthor') {
                   7566:         $envkey = $context;
                   7567:     } else {
                   7568:         $envkey = $context.'.'.$tool;
                   7569:     }
1.976     raeburn  7570: 
1.985     raeburn  7571:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7572:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7573:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7574:         $inststatus = $env{'environment.inststatus'};
                   7575:     } else {
1.1084    raeburn  7576:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7577:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7578:             $inststatus = $userenvref->{'inststatus'};
                   7579:         } else {
1.1172.2.9  raeburn  7580:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7581:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7582:             $inststatus = $userenv{'inststatus'};
                   7583:         }
1.976     raeburn  7584:     }
                   7585: 
                   7586:     if ($toolstatus ne '') {
                   7587:         if ($toolstatus) {
                   7588:             $access = 1;
                   7589:         } else {
                   7590:             $access = 0;
                   7591:         }
                   7592:         return $access;
                   7593:     }
                   7594: 
1.1084    raeburn  7595:     my ($is_adv,%domdef);
                   7596:     if (ref($is_advref) eq 'HASH') {
                   7597:         $is_adv = $is_advref->{'is_adv'};
                   7598:     } else {
                   7599:         $is_adv = &is_advanced_user($udom,$uname);
                   7600:     }
                   7601:     if (ref($domdefref) eq 'HASH') {
                   7602:         %domdef = %{$domdefref};
                   7603:     } else {
                   7604:         %domdef = &get_domain_defaults($udom);
                   7605:     }
1.976     raeburn  7606:     if (ref($domdef{$tool}) eq 'HASH') {
                   7607:         if ($is_adv) {
                   7608:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7609:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7610:                     $access = 1;
                   7611:                 } else {
                   7612:                     $access = 0;
                   7613:                 }
                   7614:                 return $access;
                   7615:             }
                   7616:         }
                   7617:         if ($inststatus ne '') {
                   7618:             my ($hasaccess,$hasnoaccess);
                   7619:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7620:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7621:                     if ($domdef{$tool}{$affiliation}) {
                   7622:                         $hasaccess = 1;
                   7623:                     } else {
                   7624:                         $hasnoaccess = 1;
                   7625:                     }
                   7626:                 }
                   7627:             }
                   7628:             if ($hasaccess || $hasnoaccess) {
                   7629:                 if ($hasaccess) {
                   7630:                     $access = 1;
                   7631:                 } elsif ($hasnoaccess) {
                   7632:                     $access = 0; 
                   7633:                 }
                   7634:                 return $access;
                   7635:             }
                   7636:         } else {
                   7637:             if ($domdef{$tool}{'default'} ne '') {
                   7638:                 if ($domdef{$tool}{'default'}) {
                   7639:                     $access = 1;
                   7640:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7641:                     $access = 0;
                   7642:                 }
                   7643:                 return $access;
                   7644:             }
                   7645:         }
                   7646:     } else {
1.1172.2.6  raeburn  7647:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7648:             $access = 1;
                   7649:         } else {
                   7650:             $access = 0;
                   7651:         }
1.976     raeburn  7652:         return $access;
                   7653:     }
                   7654: }
                   7655: 
1.1050    raeburn  7656: sub is_course_owner {
                   7657:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7658:     if (($udom eq '') || ($uname eq '')) {
                   7659:         $udom = $env{'user.domain'};
                   7660:         $uname = $env{'user.name'};
                   7661:     }
                   7662:     unless (($udom eq '') || ($uname eq '')) {
                   7663:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7664:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7665:                 return 1;
                   7666:             } else {
                   7667:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7668:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7669:                     return 1;
                   7670:                 }
                   7671:             }
                   7672:         }
                   7673:     }
                   7674:     return;
                   7675: }
                   7676: 
1.976     raeburn  7677: sub is_advanced_user {
                   7678:     my ($udom,$uname) = @_;
1.1085    raeburn  7679:     if ($udom ne '' && $uname ne '') {
                   7680:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7681:             if (wantarray) {
                   7682:                 return ($env{'user.adv'},$env{'user.author'});
                   7683:             } else {
                   7684:                 return $env{'user.adv'};
                   7685:             }
1.1085    raeburn  7686:         }
                   7687:     }
1.976     raeburn  7688:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7689:     my %allroles;
1.1128    raeburn  7690:     my ($is_adv,$is_author);
1.976     raeburn  7691:     foreach my $role (keys(%roleshash)) {
                   7692:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7693:         my $area = '/'.$tdomain.'/'.$trest;
                   7694:         if ($sec ne '') {
                   7695:             $area .= '/'.$sec;
                   7696:         }
                   7697:         if (($area ne '') && ($trole ne '')) {
                   7698:             my $spec=$trole.'.'.$area;
                   7699:             if ($trole =~ /^cr\//) {
                   7700:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7701:             } elsif ($trole ne 'gr') {
                   7702:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7703:             }
1.1128    raeburn  7704:             if ($trole eq 'au') {
                   7705:                 $is_author = 1;
                   7706:             }
1.976     raeburn  7707:         }
                   7708:     }
                   7709:     foreach my $role (keys(%allroles)) {
                   7710:         last if ($is_adv);
                   7711:         foreach my $item (split(/:/,$allroles{$role})) {
                   7712:             if ($item ne '') {
                   7713:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7714:                 if ($privilege eq 'adv') {
                   7715:                     $is_adv = 1;
                   7716:                     last;
                   7717:                 }
                   7718:             }
                   7719:         }
                   7720:     }
1.1128    raeburn  7721:     if (wantarray) {
                   7722:         return ($is_adv,$is_author);
                   7723:     }
1.976     raeburn  7724:     return $is_adv;
                   7725: }
1.798     raeburn  7726: 
1.1035    raeburn  7727: sub check_can_request {
1.1036    raeburn  7728:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7729:     my $canreq = 0;
                   7730:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7731:     my @options = ('approval','validate','autolimit');
                   7732:     my $optregex = join('|',@options);
                   7733:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7734:         foreach my $type (@{$types}) {
                   7735:             if (&usertools_access($env{'user.name'},
                   7736:                                   $env{'user.domain'},
                   7737:                                   $type,undef,'requestcourses')) {
                   7738:                 $canreq ++;
1.1036    raeburn  7739:                 if (ref($request_domains) eq 'HASH') {
                   7740:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7741:                 }
1.1035    raeburn  7742:                 if ($dom eq $env{'user.domain'}) {
                   7743:                     $can_request->{$type} = 1;
                   7744:                 }
                   7745:             }
                   7746:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7747:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7748:                 if (@curr > 0) {
1.1036    raeburn  7749:                     foreach my $item (@curr) {
                   7750:                         if (ref($request_domains) eq 'HASH') {
                   7751:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7752:                             if ($otherdom ne '') {
                   7753:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7754:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7755:                                         push(@{$request_domains->{$type}},$otherdom);
                   7756:                                     }
                   7757:                                 } else {
                   7758:                                     push(@{$request_domains->{$type}},$otherdom);
                   7759:                                 }
                   7760:                             }
                   7761:                         }
                   7762:                     }
                   7763:                     unless($dom eq $env{'user.domain'}) {
                   7764:                         $canreq ++;
1.1035    raeburn  7765:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7766:                             $can_request->{$type} = 1;
                   7767:                         }
                   7768:                     }
                   7769:                 }
                   7770:             }
                   7771:         }
                   7772:     }
                   7773:     return $canreq;
                   7774: }
                   7775: 
1.341     www      7776: # ---------------------------------------------- Custom access rule evaluation
                   7777: 
                   7778: sub customaccess {
                   7779:     my ($priv,$uri)=@_;
1.807     albertel 7780:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7781:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7782:     $udom = &LONCAPA::clean_domain($udom);
                   7783:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7784:     my $access=0;
1.800     albertel 7785:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7786: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7787: 	if ($type eq 'user') {
                   7788: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7789: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7790: 		if ($tdom) {
                   7791: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7792: 		}
1.896     albertel 7793: 		if ($tuname) {
                   7794: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7795: 		}
                   7796: 		$access=($effect eq 'allow');
                   7797: 		last;
                   7798: 	    }
                   7799: 	} else {
                   7800: 	    if ($role) {
                   7801: 		if ($role ne $urole) { next; }
                   7802: 	    }
                   7803: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7804: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7805: 		if ($tdom) {
                   7806: 		    if ($tdom ne $udom) { next; }
                   7807: 		}
                   7808: 		if ($tcrs) {
                   7809: 		    if ($tcrs ne $ucrs) { next; }
                   7810: 		}
                   7811: 		if ($tsec) {
                   7812: 		    if ($tsec ne $usec) { next; }
                   7813: 		}
                   7814: 		$access=($effect eq 'allow');
                   7815: 		last;
                   7816: 	    }
                   7817: 	    if ($realm eq '' && $role eq '') {
                   7818: 		$access=($effect eq 'allow');
                   7819: 	    }
1.402     bowersj2 7820: 	}
1.341     www      7821:     }
                   7822:     return $access;
                   7823: }
                   7824: 
1.103     harris41 7825: # ------------------------------------------------- Check for a user privilege
1.12      www      7826: 
                   7827: sub allowed {
1.1172.2.126  raeburn  7828:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7829:     my $ver_orguri=$uri;
1.439     www      7830:     $uri=&deversion($uri);
1.152     www      7831:     my $orguri=$uri;
1.52      www      7832:     $uri=&declutter($uri);
1.809     raeburn  7833: 
1.810     raeburn  7834:     if ($priv eq 'evb') {
                   7835: # Evade communication block restrictions for specified role in a course
                   7836:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7837:             return $1;
                   7838:         } else {
                   7839:             return;
                   7840:         }
                   7841:     }
                   7842: 
1.620     albertel 7843:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7844: # Free bre access to adm and meta resources
1.1172.2.133  raeburn  7845:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
1.769     albertel 7846: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7847: 	&& ($priv eq 'bre')) {
1.14      www      7848: 	return 'F';
1.159     www      7849:     }
                   7850: 
1.545     banghart 7851: # Free bre access to user's own portfolio contents
1.714     raeburn  7852:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7853:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7854: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7855:         my %setters;
                   7856:         my ($startblock,$endblock) = 
                   7857:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7858:         if ($startblock && $endblock) {
                   7859:             return 'B';
                   7860:         } else {
                   7861:             return 'F';
                   7862:         }
1.545     banghart 7863:     }
                   7864: 
1.762     raeburn  7865: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7866:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7867:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7868:         if (exists($env{'request.course.id'})) {
                   7869:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7870:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7871:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7872:                 my $courseprivid=$env{'request.course.id'};
                   7873:                 $courseprivid=~s/\_/\//;
                   7874:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7875:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7876:                     return $1; 
1.762     raeburn  7877:                 } else {
                   7878:                     if ($env{'request.course.sec'}) {
                   7879:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7880:                     }
                   7881:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7882:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7883:                         return $2;
                   7884:                     }
1.714     raeburn  7885:                 }
                   7886:             }
                   7887:         }
                   7888:     }
                   7889: 
1.159     www      7890: # Free bre to public access
                   7891: 
                   7892:     if ($priv eq 'bre') {
1.238     www      7893:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7894: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7895:            return 'F'; 
                   7896:         }
1.238     www      7897:         if ($copyright eq 'priv') {
                   7898:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7899: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7900: 		return '';
                   7901:             }
                   7902:         }
                   7903:         if ($copyright eq 'domain') {
                   7904:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7905: 	    unless (($env{'user.domain'} eq $1) ||
                   7906:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7907: 		return '';
                   7908:             }
1.262     matthew  7909:         }
1.620     albertel 7910:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7911:             # Library role, so allow browsing of resources in this domain.
                   7912:             return 'F';
1.238     www      7913:         }
1.341     www      7914:         if ($copyright eq 'custom') {
                   7915: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7916:         }
1.14      www      7917:     }
1.264     matthew  7918:     # Domain coordinator is trying to create a course
1.620     albertel 7919:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7920:         # uri is the requested domain in this case.
                   7921:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7922:         # a role of dc for the domain in question.
1.620     albertel 7923:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7924:     }
1.29      www      7925: 
1.52      www      7926:     my $thisallowed='';
                   7927:     my $statecond=0;
                   7928:     my $courseprivid='';
                   7929: 
1.1039    raeburn  7930:     my $ownaccess;
1.1043    raeburn  7931:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7932:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7933:         if ($uri eq '') {
                   7934:             $ownaccess = 1;
                   7935:         } else {
                   7936:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7937:                 my $udom = $env{'user.domain'};
                   7938:                 my $uname = $env{'user.name'};
                   7939:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7940:                     $ownaccess = 1;
1.1040    raeburn  7941:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7942:                     unless ($uri =~ m{\.\./}) {
                   7943:                         $ownaccess = 1;
                   7944:                     }
                   7945:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7946:                     my $now = time;
                   7947:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7948:                         my $adom = $1;
                   7949:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7950:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7951:                                 my ($start,$end) = split('.',$env{$key});
                   7952:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7953:                                     $ownaccess = 1;
                   7954:                                     last;
                   7955:                                 }
                   7956:                             }
                   7957:                         }
                   7958:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7959:                         my $adom = $1;
                   7960:                         my $aname = $2;
1.1042    raeburn  7961:                         foreach my $role ('ca','aa') { 
                   7962:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7963:                                 my ($start,$end) =
                   7964:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7965:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7966:                                     $ownaccess = 1;
                   7967:                                     last;
                   7968:                                 }
1.1039    raeburn  7969:                             }
                   7970:                         }
                   7971:                     }
                   7972:                 }
                   7973:             }
                   7974:         }
                   7975:     }
                   7976: 
1.52      www      7977: # Course
                   7978: 
1.620     albertel 7979:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7980:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7981:             $thisallowed.=$1;
                   7982:         }
1.52      www      7983:     }
1.29      www      7984: 
1.52      www      7985: # Domain
                   7986: 
1.620     albertel 7987:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7988:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7989:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7990:             $thisallowed.=$1;
                   7991:         }
1.12      www      7992:     }
1.52      www      7993: 
1.1141    raeburn  7994: # User who is not author or co-author might still be able to edit
                   7995: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7996:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7997:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7998:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7999:             $thisallowed.=$1;
                   8000:         }
                   8001:     }
                   8002: 
1.52      www      8003: # Course: uri itself is a course
1.66      www      8004:     my $courseuri=$uri;
                   8005:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8006:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8007: 
1.620     albertel 8008:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8009:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8010:         if ($priv eq 'mip') {
                   8011:             my $rem = $1;
                   8012:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8013:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8014:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8015:                 if ($cdom ne '') {
                   8016:                     my %passwdconf = &get_passwdconf($cdom);
                   8017:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8018:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8019:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8020:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8021:                                 unless (@inststatuses) {
                   8022:                                     @inststatuses = ('default');
                   8023:                                 }
                   8024:                                 foreach my $status (@inststatuses) {
                   8025:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8026:                                         $thisallowed.=$rem;
                   8027:                                     }
                   8028:                                 }
                   8029:                             }
                   8030:                         }
                   8031:                     }
                   8032:                 }
                   8033:             }
                   8034:         } else {
                   8035:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8036:                 $thisallowed.=$1;
                   8037:             }
1.1039    raeburn  8038:         }
1.12      www      8039:     }
1.29      www      8040: 
1.665     albertel 8041: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8042: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8043:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8044: 	$thisallowed='';
1.671     raeburn  8045:         my ($match)=&is_on_map($uri);
                   8046:         if ($match) {
                   8047:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8048:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8049:                 my $value = $1;
                   8050:                 if ($noblockcheck) {
                   8051:                     $thisallowed.=$value;
1.1162    raeburn  8052:                 } else {
1.1172.2.126  raeburn  8053:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8054:                     if (@blockers > 0) {
                   8055:                         $thisallowed = 'B';
                   8056:                     } else {
                   8057:                         $thisallowed.=$value;
                   8058:                     }
1.1162    raeburn  8059:                 }
1.671     raeburn  8060:             }
                   8061:         } else {
1.705     albertel 8062:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8063:             if ($refuri) {
                   8064:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8065:                     $thisallowed='F';
1.671     raeburn  8066:                 } else {
                   8067:                     $refuri=&declutter($refuri);
                   8068:                     my ($match) = &is_on_map($refuri);
                   8069:                     if ($match) {
1.1172.2.65  raeburn  8070:                         if ($noblockcheck) {
1.1162    raeburn  8071:                             $thisallowed='F';
1.1172.2.65  raeburn  8072:                         } else {
1.1172.2.127  raeburn  8073:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8074:                             if (@blockers > 0) {
                   8075:                                 $thisallowed = 'B';
                   8076:                             } else {
                   8077:                                 $thisallowed='F';
                   8078:                             }
1.1162    raeburn  8079:                         }
1.671     raeburn  8080:                     }
1.669     raeburn  8081:                 }
1.671     raeburn  8082:             }
                   8083:         }
1.314     www      8084:     }
1.492     albertel 8085: 
1.766     albertel 8086:     if ($priv eq 'bre'
                   8087: 	&& $thisallowed ne 'F' 
                   8088: 	&& $thisallowed ne '2'
                   8089: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8090: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8091:     }
                   8092:     
1.52      www      8093: # Full access at system, domain or course-wide level? Exit.
1.29      www      8094:     if ($thisallowed=~/F/) {
                   8095: 	return 'F';
                   8096:     }
                   8097: 
1.52      www      8098: # If this is generating or modifying users, exit with special codes
1.29      www      8099: 
1.643     www      8100:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8101: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8102: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8103: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8104: 	    unless ($auname) { return $thisallowed; }
                   8105: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8106: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8107: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8108: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8109: 	}
1.52      www      8110: 	return $thisallowed;
                   8111:     }
                   8112: #
1.103     harris41 8113: # Gathered so far: system, domain and course wide privileges
1.52      www      8114: #
                   8115: # Course: See if uri or referer is an individual resource that is part of 
                   8116: # the course
                   8117: 
1.620     albertel 8118:     if ($env{'request.course.id'}) {
1.232     www      8119: 
1.1172.2.115  raeburn  8120: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8121: 
                   8122:         if ($priv eq 'mip') {
                   8123:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8124:                 return $thisallowed;
                   8125:             } else {
                   8126:                 return '';
                   8127:             }
                   8128:         }
                   8129: 
1.620     albertel 8130:        $courseprivid=$env{'request.course.id'};
                   8131:        if ($env{'request.course.sec'}) {
                   8132:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8133:        }
                   8134:        $courseprivid=~s/\_/\//;
                   8135:        my $checkreferer=1;
1.232     www      8136:        my ($match,$cond)=&is_on_map($uri);
                   8137:        if ($match) {
                   8138:            $statecond=$cond;
1.620     albertel 8139:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8140:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8141:                my $value = $1;
                   8142:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8143:                    if ($noblockcheck) {
1.1162    raeburn  8144:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8145:                    } else {
1.1172.2.126  raeburn  8146:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8147:                        if (@blockers > 0) {
                   8148:                            $thisallowed = 'B';
                   8149:                        } else {
                   8150:                            $thisallowed.=$value;
                   8151:                        }
1.1162    raeburn  8152:                    }
                   8153:                } else {
                   8154:                    $thisallowed.=$value;
                   8155:                }
1.52      www      8156:                $checkreferer=0;
                   8157:            }
1.29      www      8158:        }
1.1172.2.126  raeburn  8159: 
1.148     www      8160:        if ($checkreferer) {
1.620     albertel 8161: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8162:             unless ($refuri) {
1.800     albertel 8163:                 foreach my $key (keys(%env)) {
                   8164: 		    if ($key=~/^httpref\..*\*/) {
                   8165: 			my $pattern=$key;
1.156     www      8166:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8167:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8168:                         $pattern=~s/\//\\\//g;
1.152     www      8169:                         if ($orguri=~/$pattern/) {
1.800     albertel 8170: 			    $refuri=$env{$key};
1.148     www      8171:                         }
                   8172:                     }
1.191     harris41 8173:                 }
1.148     www      8174:             }
1.232     www      8175: 
1.148     www      8176:          if ($refuri) { 
1.152     www      8177: 	  $refuri=&declutter($refuri);
1.232     www      8178:           my ($match,$cond)=&is_on_map($refuri);
                   8179:             if ($match) {
                   8180:               my $refstatecond=$cond;
1.620     albertel 8181:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8182:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8183:                   my $value = $1;
                   8184:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8185:                       if ($noblockcheck) {
1.1162    raeburn  8186:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8187:                       } else {
1.1172.2.127  raeburn  8188:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8189:                           if (@blockers > 0) {
                   8190:                               $thisallowed = 'B';
                   8191:                           } else {
                   8192:                               $thisallowed.=$value;
                   8193:                           }
1.1162    raeburn  8194:                       }
                   8195:                   } else {
                   8196:                       $thisallowed.=$value;
                   8197:                   }
1.53      www      8198:                   $uri=$refuri;
                   8199:                   $statecond=$refstatecond;
1.52      www      8200:               }
                   8201:           }
1.148     www      8202:         }
1.29      www      8203:        }
1.52      www      8204:    }
1.29      www      8205: 
1.52      www      8206: #
1.103     harris41 8207: # Gathered now: all privileges that could apply, and condition number
1.52      www      8208: # 
                   8209: #
                   8210: # Full or no access?
                   8211: #
1.29      www      8212: 
1.52      www      8213:     if ($thisallowed=~/F/) {
                   8214: 	return 'F';
                   8215:     }
1.29      www      8216: 
1.52      www      8217:     unless ($thisallowed) {
                   8218:         return '';
                   8219:     }
1.29      www      8220: 
1.52      www      8221: # Restrictions exist, deal with them
                   8222: #
                   8223: #   C:according to course preferences
                   8224: #   R:according to resource settings
                   8225: #   L:unless locked
                   8226: #   X:according to user session state
                   8227: #
                   8228: 
                   8229: # Possibly locked functionality, check all courses
1.54      www      8230: # Locks might take effect only after 10 minutes cache expiration for other
                   8231: # courses, and 2 minutes for current course
1.52      www      8232: 
                   8233:     my $envkey;
                   8234:     if ($thisallowed=~/L/) {
1.1000    raeburn  8235:         foreach $envkey (keys(%env)) {
1.54      www      8236:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8237:                my $courseid=$2;
                   8238:                my $roleid=$1.'.'.$2;
1.92      www      8239:                $courseid=~s/^\///;
1.54      www      8240:                my $expiretime=600;
1.620     albertel 8241:                if ($env{'request.role'} eq $roleid) {
1.54      www      8242: 		  $expiretime=120;
                   8243:                }
                   8244: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8245:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8246:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8247: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8248:                }
1.620     albertel 8249:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8250:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8251: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8252:                        &log($env{'user.domain'},$env{'user.name'},
                   8253:                             $env{'user.home'},
1.57      www      8254:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8255:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8256:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8257: 		       return '';
                   8258:                    }
                   8259:                }
1.620     albertel 8260:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8261:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8262: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8263:                        &log($env{'user.domain'},$env{'user.name'},
                   8264:                             $env{'user.home'},
1.57      www      8265:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8266:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8267:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8268: 		       return '';
                   8269:                    }
                   8270:                }
                   8271: 	   }
1.29      www      8272:        }
1.52      www      8273:     }
1.1172.2.126  raeburn  8274: 
1.52      www      8275: #
                   8276: # Rest of the restrictions depend on selected course
                   8277: #
                   8278: 
1.620     albertel 8279:     unless ($env{'request.course.id'}) {
1.766     albertel 8280: 	if ($thisallowed eq 'A') {
                   8281: 	    return 'A';
1.814     raeburn  8282:         } elsif ($thisallowed eq 'B') {
                   8283:             return 'B';
1.766     albertel 8284: 	} else {
                   8285: 	    return '1';
                   8286: 	}
1.52      www      8287:     }
1.29      www      8288: 
1.52      www      8289: #
                   8290: # Now user is definitely in a course
                   8291: #
1.53      www      8292: 
                   8293: 
                   8294: # Course preferences
                   8295: 
                   8296:    if ($thisallowed=~/C/) {
1.620     albertel 8297:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8298:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8299:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8300: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8301: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8302: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8303: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8304: 			$env{'request.course.id'});
                   8305: 	   }
1.237     www      8306:            return '';
                   8307:        }
                   8308: 
1.620     albertel 8309:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8310: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8311: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8312: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8313: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8314: 			$env{'request.course.id'});
                   8315: 	   }
1.54      www      8316:            return '';
                   8317:        }
1.53      www      8318:    }
                   8319: 
                   8320: # Resource preferences
                   8321: 
                   8322:    if ($thisallowed=~/R/) {
1.620     albertel 8323:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8324:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8325: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8326: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8327: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8328: 	   }
                   8329: 	   return '';
1.54      www      8330:        }
1.53      www      8331:    }
1.30      www      8332: 
1.246     www      8333: # Restricted by state or randomout?
1.30      www      8334: 
1.52      www      8335:    if ($thisallowed=~/X/) {
1.620     albertel 8336:       if ($env{'acc.randomout'}) {
1.579     albertel 8337: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8338:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8339:             return ''; 
                   8340:          }
1.247     www      8341:       }
                   8342:       if (&condval($statecond)) {
1.52      www      8343: 	 return '2';
                   8344:       } else {
                   8345:          return '';
                   8346:       }
                   8347:    }
1.30      www      8348: 
1.766     albertel 8349:     if ($thisallowed eq 'A') {
                   8350: 	return 'A';
1.814     raeburn  8351:     } elsif ($thisallowed eq 'B') {
                   8352:         return 'B';
1.766     albertel 8353:     }
1.52      www      8354:    return 'F';
1.232     www      8355: }
1.1162    raeburn  8356: 
1.1172.2.13  raeburn  8357: # ------------------------------------------- Check construction space access
                   8358: 
                   8359: sub constructaccess {
                   8360:     my ($url,$setpriv)=@_;
                   8361: 
                   8362: # We do not allow editing of previous versions of files
                   8363:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8364: 
                   8365: # Get username and domain from URL
                   8366:     my ($ownername,$ownerdomain,$ownerhome);
                   8367: 
                   8368:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8369:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8370: 
                   8371: # The URL does not really point to any authorspace, forget it
                   8372:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8373: 
                   8374: # Now we need to see if the user has access to the authorspace of
                   8375: # $ownername at $ownerdomain
                   8376: 
                   8377:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8378: # Real author for this?
                   8379:        $ownerhome = $env{'user.home'};
                   8380:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8381:           return ($ownername,$ownerdomain,$ownerhome);
                   8382:        }
                   8383:     } else {
                   8384: # Co-author for this?
                   8385:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8386:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8387:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8388:             return ($ownername,$ownerdomain,$ownerhome);
                   8389:         }
                   8390:     }
                   8391: 
                   8392: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8393: # we might as well leave
                   8394:    unless ($setpriv) { return ''; }
                   8395: 
                   8396: # Backdoor access?
                   8397:     my $allowed=&allowed('eco',$ownerdomain);
                   8398: # Nope
                   8399:     unless ($allowed) { return ''; }
                   8400: # Looks like we may have access, but could be locked by the owner of the construction space
                   8401:     if ($allowed eq 'U') {
                   8402:         my %blocked=&get('environment',['domcoord.author'],
                   8403:                          $ownerdomain,$ownername);
                   8404: # Is blocked by owner
                   8405:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8406:     }
                   8407:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8408: # Grant temporary access
                   8409:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8410:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8411:         if (!$update) { $update = $then; }
                   8412:         my $refresh=$env{'user.refresh.time'};
                   8413:         if (!$refresh) { $refresh = $update; }
                   8414:         my $now = time;
                   8415:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8416:                            $now,'ca','constructaccess');
                   8417:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8418:         return($ownername,$ownerdomain,$ownerhome);
                   8419:     }
                   8420: # No business here
                   8421:     return '';
                   8422: }
                   8423: 
1.1172.2.66  raeburn  8424: # ----------------------------------------------------------- Content Blocking
                   8425: 
                   8426: {
                   8427: # Caches for faster Course Contents display where content blocking
                   8428: # is in operation (i.e., interval param set) for timed quiz.
                   8429: #
                   8430: # User for whom data are being temporarily cached.
                   8431: my $cacheduser='';
1.1172.2.126  raeburn  8432: # Course for which data are being temporarily cached.
                   8433: my $cachedcid='';
1.1172.2.66  raeburn  8434: # Cached blockers for this user (a hash of blocking items).
                   8435: my %cachedblockers=();
                   8436: # When the data were last cached.
                   8437: my $cachedlast='';
                   8438: 
                   8439: sub load_all_blockers {
1.1172.2.128  raeburn  8440:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8441:     if (($uname ne '') && ($udom ne '')) {
                   8442:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8443:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8444:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8445:             return;
                   8446:         }
                   8447:     }
                   8448:     $cachedlast=time;
                   8449:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8450:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8451:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8452:     return;
1.1172.2.66  raeburn  8453: }
                   8454: 
1.1162    raeburn  8455: sub get_comm_blocks {
                   8456:     my ($cdom,$cnum) = @_;
                   8457:     if ($cdom eq '' || $cnum eq '') {
                   8458:         return unless ($env{'request.course.id'});
                   8459:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8460:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8461:     }
                   8462:     my %commblocks;
                   8463:     my $hashid=$cdom.'_'.$cnum;
                   8464:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8465:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8466:         %commblocks = %{$blocksref};
                   8467:     } else {
                   8468:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8469:         my $cachetime = 600;
                   8470:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8471:     }
                   8472:     return %commblocks;
                   8473: }
                   8474: 
1.1172.2.66  raeburn  8475: sub get_commblock_resources {
                   8476:     my ($blocks) = @_;
                   8477:     my %blockers = ();
                   8478:     return %blockers unless ($env{'request.course.id'});
                   8479:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8480:     my %commblocks;
                   8481:     if (ref($blocks) eq 'HASH') {
                   8482:         %commblocks = %{$blocks};
                   8483:     } else {
                   8484:         %commblocks = &get_comm_blocks();
                   8485:     }
1.1172.2.66  raeburn  8486:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8487:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8488:     return %blockers unless (ref($navmap));
                   8489:     my $now = time;
1.1162    raeburn  8490:     foreach my $block (keys(%commblocks)) {
                   8491:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8492:             my ($start,$end) = ($1,$2);
                   8493:             if ($start <= $now && $end >= $now) {
                   8494:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8495:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8496:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8497:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8498:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8499:                             }
                   8500:                         }
                   8501:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8502:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8503:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8504:                             }
                   8505:                         }
                   8506:                     }
                   8507:                 }
                   8508:             }
                   8509:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8510:             my $item = $1;
1.1163    raeburn  8511:             my @to_test;
1.1162    raeburn  8512:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8513:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8514:                     my @interval;
                   8515:                     my $type = 'map';
                   8516:                     if ($item eq 'course') {
                   8517:                         $type = 'course';
                   8518:                         @interval=&EXT("resource.0.interval");
                   8519:                     } else {
                   8520:                         if ($item =~ /___\d+___/) {
                   8521:                             $type = 'resource';
                   8522:                             @interval=&EXT("resource.0.interval",$item);
                   8523:                             if (ref($navmap)) {
                   8524:                                 my $res = $navmap->getBySymb($item);
                   8525:                                 push(@to_test,$res);
                   8526:                             }
1.1162    raeburn  8527:                         } else {
1.1172.2.66  raeburn  8528:                             my $mapsymb = &symbread($item,1);
                   8529:                             if ($mapsymb) {
                   8530:                                 if (ref($navmap)) {
                   8531:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.129  raeburn  8532:                                     if (ref($mapres)) {
                   8533:                                         my $first = $mapres->map_start();
                   8534:                                         my $finish = $mapres->map_finish();
                   8535:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8536:                                         if (ref($it)) {
                   8537:                                             my $res;
                   8538:                                             while ($res = $it->next(undef,1)) {
                   8539:                                                 next unless (ref($res));
                   8540:                                                 my $symb = $res->symb();
                   8541:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8542:                                                 @interval=&EXT("resource.0.interval",$symb);
                   8543:                                                 if ($interval[1] eq 'map') {
                   8544:                                                     if ($res->answerable()) {
                   8545:                                                         push(@to_test,$res);
                   8546:                                                         last;
                   8547:                                                     }
                   8548:                                                 }
1.1162    raeburn  8549:                                             }
                   8550:                                         }
                   8551:                                     }
                   8552:                                 }
                   8553:                             }
                   8554:                         }
1.1172.2.66  raeburn  8555:                     }
                   8556:                     if ($interval[0] =~ /^\d+$/) {
                   8557:                         my $first_access;
                   8558:                         if ($type eq 'resource') {
                   8559:                             $first_access=&get_first_access($interval[1],$item);
                   8560:                         } elsif ($type eq 'map') {
                   8561:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8562:                         } else {
                   8563:                             $first_access=&get_first_access($interval[1]);
                   8564:                         }
                   8565:                         if ($first_access) {
                   8566:                             my $timesup = $first_access+$interval[0];
                   8567:                             if ($timesup > $now) {
                   8568:                                 my $activeblock;
                   8569:                                 foreach my $res (@to_test) {
                   8570:                                     if ($res->answerable()) {
                   8571:                                         $activeblock = 1;
                   8572:                                         last;
                   8573:                                     }
                   8574:                                 }
                   8575:                                 if ($activeblock) {
                   8576:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8577:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8578:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8579:                                          }
                   8580:                                     }
                   8581:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8582:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8583:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8584:                                         }
1.1162    raeburn  8585:                                     }
                   8586:                                 }
                   8587:                             }
                   8588:                         }
                   8589:                     }
                   8590:                 }
                   8591:             }
                   8592:         }
                   8593:     }
1.1172.2.66  raeburn  8594:     return %blockers;
1.1162    raeburn  8595: }
                   8596: 
1.1172.2.66  raeburn  8597: sub has_comm_blocking {
1.1172.2.128  raeburn  8598:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8599:     my @blockers;
                   8600:     return unless ($env{'request.course.id'});
                   8601:     return unless ($priv eq 'bre');
                   8602:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8603:     return if ($env{'request.state'} eq 'construct');
1.1172.2.128  raeburn  8604:     my %blockinfo;
                   8605:     if (ref($blocks) eq 'HASH') {
                   8606:         %blockinfo = &get_commblock_resources($blocks);
                   8607:     } else {
                   8608:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8609:         %blockinfo = %cachedblockers;
                   8610:     }
                   8611:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8612:     my (%possibles,@symbs);
                   8613:     if (!$symb) {
1.1172.2.128  raeburn  8614:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8615:     }
1.1172.2.66  raeburn  8616:     if ($symb) {
                   8617:         @symbs = ($symb);
                   8618:     } elsif (keys(%possibles)) {
                   8619:         @symbs = keys(%possibles);
                   8620:     }
                   8621:     my $noblock;
                   8622:     foreach my $symb (@symbs) {
                   8623:         last if ($noblock);
                   8624:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8625:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8626:             if ($block =~ /^firstaccess____(.+)$/) {
                   8627:                 my $item = $1;
1.1172.2.126  raeburn  8628:                 unless ($blocked) {
                   8629:                     if (($item eq $map) || ($item eq $symb)) {
                   8630:                         $noblock = 1;
                   8631:                         last;
                   8632:                     }
1.1172.2.66  raeburn  8633:                 }
1.1162    raeburn  8634:             }
1.1172.2.128  raeburn  8635:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8636:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8637:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8638:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8639:                             push(@blockers,$block);
                   8640:                         }
                   8641:                     }
                   8642:                 }
1.1172.2.128  raeburn  8643:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8644:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8645:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8646:                             push(@blockers,$block);
                   8647:                         }
1.1172.2.66  raeburn  8648:                     }
                   8649:                 }
1.1162    raeburn  8650:             }
                   8651:         }
                   8652:     }
1.1172.2.126  raeburn  8653:     unless ($noblock) {
                   8654:         return @blockers;
                   8655:     }
                   8656:     return;
1.1172.2.66  raeburn  8657: }
1.1162    raeburn  8658: }
                   8659: 
1.1172.2.66  raeburn  8660: # -------------------------------- Deversion and split uri into path an filename
                   8661: 
1.1133    foxr     8662: #
1.1172.2.66  raeburn  8663: #   Removes the version from a URI and
1.1133    foxr     8664: #   splits it in to its filename and path to the filename.
                   8665: #   Seems like File::Basename could have done this more clearly.
                   8666: #   Parameters:
                   8667: #      $uri   - input URI
                   8668: #   Returns:
                   8669: #     Two element list consisting of 
                   8670: #     $pathname  - the URI up to and excluding the trailing /
                   8671: #     $filename  - The part of the URI following the last /
                   8672: #  NOTE:
                   8673: #    Another realization of this is simply:
                   8674: #    use File::Basename;
                   8675: #    ...
                   8676: #    $uri = shift;
                   8677: #    $filename = basename($uri);
                   8678: #    $path     = dirname($uri);
                   8679: #    return ($filename, $path);
                   8680: #
                   8681: #     The implementation below is probably faster however.
                   8682: #
1.710     albertel 8683: sub split_uri_for_cond {
                   8684:     my $uri=&deversion(&declutter(shift));
                   8685:     my @uriparts=split(/\//,$uri);
                   8686:     my $filename=pop(@uriparts);
                   8687:     my $pathname=join('/',@uriparts);
                   8688:     return ($pathname,$filename);
                   8689: }
1.232     www      8690: # --------------------------------------------------- Is a resource on the map?
                   8691: 
                   8692: sub is_on_map {
1.710     albertel 8693:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8694:     #Trying to find the conditional for the file
1.620     albertel 8695:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8696: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8697:     if ($match) {
1.289     bowersj2 8698: 	return (1,$1);
                   8699:     } else {
1.434     www      8700: 	return (0,0);
1.289     bowersj2 8701:     }
1.12      www      8702: }
                   8703: 
1.427     www      8704: # --------------------------------------------------------- Get symb from alias
                   8705: 
                   8706: sub get_symb_from_alias {
                   8707:     my $symb=shift;
                   8708:     my ($map,$resid,$url)=&decode_symb($symb);
                   8709: # Already is a symb
                   8710:     if ($url) { return $symb; }
                   8711: # Must be an alias
                   8712:     my $aliassymb='';
                   8713:     my %bighash;
1.620     albertel 8714:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8715:                             &GDBM_READER(),0640)) {
                   8716:         my $rid=$bighash{'mapalias_'.$symb};
                   8717: 	if ($rid) {
                   8718: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8719: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8720: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8721: 	}
                   8722:         untie %bighash;
                   8723:     }
                   8724:     return $aliassymb;
                   8725: }
                   8726: 
1.12      www      8727: # ----------------------------------------------------------------- Define Role
                   8728: 
                   8729: sub definerole {
                   8730:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8731:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8732:     foreach my $role (split(':',$sysrole)) {
                   8733: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8734:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8735:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8736: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8737:                return "refused:s:$crole&$cqual"; 
                   8738:             }
                   8739:         }
1.191     harris41 8740:     }
1.800     albertel 8741:     foreach my $role (split(':',$domrole)) {
                   8742: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8743:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8744:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8745: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8746:                return "refused:d:$crole&$cqual"; 
                   8747:             }
                   8748:         }
1.191     harris41 8749:     }
1.800     albertel 8750:     foreach my $role (split(':',$courole)) {
                   8751: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8752:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8753:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8754: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8755:                return "refused:c:$crole&$cqual"; 
                   8756:             }
                   8757:         }
1.191     harris41 8758:     }
1.1172.2.84  raeburn  8759:     my $uhome;
                   8760:     if (($uname ne '') && ($udom ne '')) {
                   8761:         $uhome = &homeserver($uname,$udom);
                   8762:         return $uhome if ($uhome eq 'no_host');
                   8763:     } else {
                   8764:         $uname = $env{'user.name'};
                   8765:         $udom = $env{'user.domain'};
                   8766:         $uhome = $env{'user.home'};
                   8767:     }
1.620     albertel 8768:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8769:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8770:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8771:     return reply($command,$uhome);
1.12      www      8772:   } else {
                   8773:     return 'refused';
                   8774:   }
1.105     harris41 8775: }
                   8776: 
                   8777: # ---------------- Make a metadata query against the network of library servers
                   8778: 
                   8779: sub metadata_query {
1.1172.2.33  raeburn  8780:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8781:     my %rhash;
1.845     albertel 8782:     my %libserv = &all_library();
1.244     matthew  8783:     my @server_list = (defined($server_array) ? @$server_array
                   8784:                                               : keys(%libserv) );
                   8785:     for my $server (@server_list) {
1.1172.2.33  raeburn  8786:         my $domains = '';
                   8787:         if (ref($domains_hash) eq 'HASH') {
                   8788:             $domains = $domains_hash->{$server};    
                   8789:         }
1.118     harris41 8790: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8791: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8792: 	    $rhash{$server}=$reply;
                   8793: 	}
                   8794: 	else {
                   8795: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8796: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8797: 			     $server);
                   8798: 	    $rhash{$server}=$reply;
                   8799: 	}
1.112     harris41 8800:     }
1.118     harris41 8801:     return \%rhash;
1.240     www      8802: }
                   8803: 
                   8804: # ----------------------------------------- Send log queries and wait for reply
                   8805: 
                   8806: sub log_query {
                   8807:     my ($uname,$udom,$query,%filters)=@_;
                   8808:     my $uhome=&homeserver($uname,$udom);
                   8809:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8810:     my $uhost=&hostname($uhome);
1.800     albertel 8811:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8812:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8813:                        $uhome);
1.479     albertel 8814:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8815:     return get_query_reply($queryid);
                   8816: }
                   8817: 
1.818     raeburn  8818: # -------------------------- Update MySQL table for portfolio file
                   8819: 
                   8820: sub update_portfolio_table {
1.821     raeburn  8821:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8822:     if ($group ne '') {
                   8823:         $file_name =~s /^\Q$group\E//;
                   8824:     }
1.818     raeburn  8825:     my $homeserver = &homeserver($uname,$udom);
                   8826:     my $queryid=
1.821     raeburn  8827:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8828:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8829:     my $reply = &get_query_reply($queryid);
                   8830:     return $reply;
                   8831: }
                   8832: 
1.899     raeburn  8833: # -------------------------- Update MySQL allusers table
                   8834: 
                   8835: sub update_allusers_table {
                   8836:     my ($uname,$udom,$names) = @_;
                   8837:     my $homeserver = &homeserver($uname,$udom);
                   8838:     my $queryid=
                   8839:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8840:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8841:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8842:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8843:                'generation='.&escape($names->{'generation'}).'%%'.
                   8844:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8845:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8846:     return;
1.899     raeburn  8847: }
                   8848: 
1.508     raeburn  8849: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8850: 
                   8851: sub fetch_enrollment_query {
1.511     raeburn  8852:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8853:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8854:     my $maxtries = 1;
1.508     raeburn  8855:     if ($context eq 'automated') {
                   8856:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8857:         $sleep = 2;
                   8858:         $loopmax = 100;
1.547     raeburn  8859:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8860:     } else {
                   8861:         $homeserver = &homeserver($cnum,$dom);
                   8862:     }
1.838     albertel 8863:     my $host=&hostname($homeserver);
1.506     raeburn  8864:     my $cmd = '';
1.1000    raeburn  8865:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8866:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8867:     }
                   8868:     $cmd =~ s/%%$//;
                   8869:     $cmd = &escape($cmd);
                   8870:     my $query = 'fetchenrollment';
1.620     albertel 8871:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8872:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8873:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8874:         return 'error: '.$queryid;
                   8875:     }
1.1172.2.93  raeburn  8876:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8877:     my $tries = 1;
                   8878:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8879:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8880:         $tries ++;
                   8881:     }
1.526     raeburn  8882:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8883:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8884:     } else {
1.901     albertel 8885:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8886:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8887:             foreach my $line (@responses) {
                   8888:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8889:                 $$replyref{$key} = $value;
                   8890:             }
                   8891:         } else {
1.1117    foxr     8892:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8893:             foreach my $line (@responses) {
                   8894:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8895:                 $$replyref{$key} = $value;
                   8896:                 if ($value > 0) {
1.800     albertel 8897:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8898:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8899:                         my $destname = $pathname.'/'.$filename;
                   8900:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8901:                         if ($xml_classlist =~ /^error/) {
                   8902:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8903:                         } else {
1.1172.2.96  raeburn  8904:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8905:                                 print FILE &unescape($xml_classlist);
                   8906:                                 close(FILE);
1.526     raeburn  8907:                             } else {
                   8908:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8909:                             }
                   8910:                         }
                   8911:                     }
                   8912:                 }
                   8913:             }
                   8914:         }
                   8915:         return 'ok';
                   8916:     }
                   8917:     return 'error';
                   8918: }
                   8919: 
1.242     www      8920: sub get_query_reply {
1.1172.2.79  raeburn  8921:     my ($queryid,$sleep,$loopmax) = @_;
                   8922:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8923:         $sleep = 0.2;
                   8924:     }
                   8925:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8926:         $loopmax = 100;
                   8927:     }
1.1117    foxr     8928:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8929:     my $reply='';
1.1172.2.79  raeburn  8930:     for (1..$loopmax) {
                   8931: 	sleep($sleep);
1.240     www      8932:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8933: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8934: 		$reply = join('',<$fh>);
                   8935: 		close($fh);
1.240     www      8936: 	   } else { return 'error: reply_file_error'; }
1.242     www      8937:            return &unescape($reply);
                   8938: 	}
1.240     www      8939:     }
1.242     www      8940:     return 'timeout:'.$queryid;
1.240     www      8941: }
                   8942: 
                   8943: sub courselog_query {
1.241     www      8944: #
                   8945: # possible filters:
                   8946: # url: url or symb
                   8947: # username
                   8948: # domain
                   8949: # action: view, submit, grade
                   8950: # start: timestamp
                   8951: # end: timestamp
                   8952: #
1.240     www      8953:     my (%filters)=@_;
1.620     albertel 8954:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8955:     if ($filters{'url'}) {
                   8956: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8957:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8958:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8959:     }
1.620     albertel 8960:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8961:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8962:     return &log_query($cname,$cdom,'courselog',%filters);
                   8963: }
                   8964: 
                   8965: sub userlog_query {
1.858     raeburn  8966: #
                   8967: # possible filters:
                   8968: # action: log check role
                   8969: # start: timestamp
                   8970: # end: timestamp
                   8971: #
1.240     www      8972:     my ($uname,$udom,%filters)=@_;
                   8973:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8974: }
                   8975: 
1.506     raeburn  8976: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8977: 
                   8978: sub auto_run {
1.508     raeburn  8979:     my ($cnum,$cdom) = @_;
1.876     raeburn  8980:     my $response = 0;
                   8981:     my $settings;
                   8982:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8983:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8984:         $settings = $domconfig{'autoenroll'};
                   8985:         if ($settings->{'run'} eq '1') {
                   8986:             $response = 1;
                   8987:         }
                   8988:     } else {
1.934     raeburn  8989:         my $homeserver;
                   8990:         if (&is_course($cdom,$cnum)) {
                   8991:             $homeserver = &homeserver($cnum,$cdom);
                   8992:         } else {
                   8993:             $homeserver = &domain($cdom,'primary');
                   8994:         }
                   8995:         if ($homeserver ne 'no_host') {
                   8996:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8997:         }
1.876     raeburn  8998:     }
1.506     raeburn  8999:     return $response;
                   9000: }
1.776     albertel 9001: 
1.506     raeburn  9002: sub auto_get_sections {
1.508     raeburn  9003:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9004:     my $homeserver;
                   9005:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9006:         $homeserver = &homeserver($cnum,$cdom);
                   9007:     }
                   9008:     if (!defined($homeserver)) { 
                   9009:         if ($cdom =~ /^$match_domain$/) {
                   9010:             $homeserver = &domain($cdom,'primary');
                   9011:         }
                   9012:     }
                   9013:     my @secs;
                   9014:     if (defined($homeserver)) {
                   9015:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9016:         unless ($response eq 'refused') {
                   9017:             @secs = split(/:/,$response);
                   9018:         }
1.506     raeburn  9019:     }
                   9020:     return @secs;
                   9021: }
1.776     albertel 9022: 
1.506     raeburn  9023: sub auto_new_course {
1.1099    raeburn  9024:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9025:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9026:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9027:     return $response;
                   9028: }
1.776     albertel 9029: 
1.506     raeburn  9030: sub auto_validate_courseID {
1.508     raeburn  9031:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9032:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9033:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9034:     return $response;
                   9035: }
1.776     albertel 9036: 
1.1007    raeburn  9037: sub auto_validate_instcode {
1.1020    raeburn  9038:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9039:     my ($homeserver,$response);
                   9040:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9041:         $homeserver = &homeserver($cnum,$cdom);
                   9042:     }
                   9043:     if (!defined($homeserver)) {
                   9044:         if ($cdom =~ /^$match_domain$/) {
                   9045:             $homeserver = &domain($cdom,'primary');
                   9046:         }
                   9047:     }
1.1065    raeburn  9048:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9049:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9050:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9051:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9052: }
                   9053: 
1.506     raeburn  9054: sub auto_create_password {
1.873     raeburn  9055:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9056:     my ($homeserver,$response);
1.506     raeburn  9057:     my $create_passwd = 0;
                   9058:     my $authchk = '';
1.873     raeburn  9059:     if ($udom =~ /^$match_domain$/) {
                   9060:         $homeserver = &domain($udom,'primary');
                   9061:     }
                   9062:     if ($homeserver eq '') {
                   9063:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9064:             $homeserver = &homeserver($cnum,$cdom);
                   9065:         }
                   9066:     }
                   9067:     if ($homeserver eq '') {
                   9068:         $authchk = 'nodomain';
1.506     raeburn  9069:     } else {
1.873     raeburn  9070:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9071:         if ($response eq 'refused') {
                   9072:             $authchk = 'refused';
                   9073:         } else {
1.901     albertel 9074:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9075:         }
1.506     raeburn  9076:     }
                   9077:     return ($authparam,$create_passwd,$authchk);
                   9078: }
                   9079: 
1.706     raeburn  9080: sub auto_photo_permission {
                   9081:     my ($cnum,$cdom,$students) = @_;
                   9082:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9083:     my ($outcome,$perm_reqd,$conditions) = 
                   9084: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9085:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9086: 	return (undef,undef);
                   9087:     }
1.706     raeburn  9088:     return ($outcome,$perm_reqd,$conditions);
                   9089: }
                   9090: 
                   9091: sub auto_checkphotos {
                   9092:     my ($uname,$udom,$pid) = @_;
                   9093:     my $homeserver = &homeserver($uname,$udom);
                   9094:     my ($result,$resulttype);
                   9095:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9096: 				   &escape($uname).':'.&escape($pid),
                   9097: 				   $homeserver));
1.709     albertel 9098:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9099: 	return (undef,undef);
                   9100:     }
1.706     raeburn  9101:     if ($outcome) {
                   9102:         ($result,$resulttype) = split(/:/,$outcome);
                   9103:     } 
                   9104:     return ($result,$resulttype);
                   9105: }
                   9106: 
                   9107: sub auto_photochoice {
                   9108:     my ($cnum,$cdom) = @_;
                   9109:     my $homeserver = &homeserver($cnum,$cdom);
                   9110:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9111: 						       &escape($cdom),
                   9112: 						       $homeserver)));
1.709     albertel 9113:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9114: 	return (undef,undef);
                   9115:     }
1.706     raeburn  9116:     return ($update,$comment);
                   9117: }
                   9118: 
                   9119: sub auto_photoupdate {
                   9120:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9121:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9122:     my $host=&hostname($homeserver);
1.706     raeburn  9123:     my $cmd = '';
                   9124:     my $maxtries = 1;
1.800     albertel 9125:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9126:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9127:     }
                   9128:     $cmd =~ s/%%$//;
                   9129:     $cmd = &escape($cmd);
                   9130:     my $query = 'institutionalphotos';
                   9131:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9132:     unless ($queryid=~/^\Q$host\E\_/) {
                   9133:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9134:         return 'error: '.$queryid;
                   9135:     }
                   9136:     my $reply = &get_query_reply($queryid);
                   9137:     my $tries = 1;
                   9138:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9139:         $reply = &get_query_reply($queryid);
                   9140:         $tries ++;
                   9141:     }
                   9142:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9143:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9144:     } else {
                   9145:         my @responses = split(/:/,$reply);
                   9146:         my $outcome = shift(@responses); 
                   9147:         foreach my $item (@responses) {
                   9148:             my ($key,$value) = split(/=/,$item);
                   9149:             $$photo{$key} = $value;
                   9150:         }
                   9151:         return $outcome;
                   9152:     }
                   9153:     return 'error';
                   9154: }
                   9155: 
1.521     raeburn  9156: sub auto_instcode_format {
1.793     albertel 9157:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9158: 	$cat_order) = @_;
1.521     raeburn  9159:     my $courses = '';
1.772     raeburn  9160:     my @homeservers;
1.521     raeburn  9161:     if ($caller eq 'global') {
1.841     albertel 9162: 	my %servers = &get_servers($codedom,'library');
                   9163: 	foreach my $tryserver (keys(%servers)) {
                   9164: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9165: 		push(@homeservers,$tryserver);
                   9166: 	    }
1.584     raeburn  9167:         }
1.1022    raeburn  9168:     } elsif ($caller eq 'requests') {
                   9169:         if ($codedom =~ /^$match_domain$/) {
                   9170:             my $chome = &domain($codedom,'primary');
                   9171:             unless ($chome eq 'no_host') {
                   9172:                 push(@homeservers,$chome);
                   9173:             }
                   9174:         }
1.521     raeburn  9175:     } else {
1.772     raeburn  9176:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9177:     }
1.793     albertel 9178:     foreach my $code (keys(%{$instcodes})) {
                   9179:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9180:     }
                   9181:     chop($courses);
1.772     raeburn  9182:     my $ok_response = 0;
                   9183:     my $response;
                   9184:     while (@homeservers > 0 && $ok_response == 0) {
                   9185:         my $server = shift(@homeservers); 
                   9186:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9187:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9188:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9189: 		split(/:/,$response);
1.772     raeburn  9190:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9191:             push(@{$codetitles},&str2array($codetitles_str));
                   9192:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9193:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9194:             $ok_response = 1;
                   9195:         }
                   9196:     }
                   9197:     if ($ok_response) {
1.521     raeburn  9198:         return 'ok';
1.772     raeburn  9199:     } else {
                   9200:         return $response;
1.521     raeburn  9201:     }
                   9202: }
                   9203: 
1.792     raeburn  9204: sub auto_instcode_defaults {
                   9205:     my ($domain,$returnhash,$code_order) = @_;
                   9206:     my @homeservers;
1.841     albertel 9207: 
                   9208:     my %servers = &get_servers($domain,'library');
                   9209:     foreach my $tryserver (keys(%servers)) {
                   9210: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9211: 	    push(@homeservers,$tryserver);
                   9212: 	}
1.792     raeburn  9213:     }
1.841     albertel 9214: 
1.792     raeburn  9215:     my $response;
1.841     albertel 9216:     foreach my $server (@homeservers) {
1.792     raeburn  9217:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9218:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9219: 	
                   9220: 	foreach my $pair (split(/\&/,$response)) {
                   9221: 	    my ($name,$value)=split(/\=/,$pair);
                   9222: 	    if ($name eq 'code_order') {
                   9223: 		@{$code_order} = split(/\&/,&unescape($value));
                   9224: 	    } else {
                   9225: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9226: 	    }
                   9227: 	}
                   9228: 	return 'ok';
1.792     raeburn  9229:     }
1.841     albertel 9230: 
                   9231:     return $response;
1.1003    raeburn  9232: }
                   9233: 
                   9234: sub auto_possible_instcodes {
1.1007    raeburn  9235:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9236:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9237:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9238:         return;
                   9239:     }
1.1003    raeburn  9240:     my (@homeservers,$uhome);
                   9241:     if (defined(&domain($domain,'primary'))) {
                   9242:         $uhome=&domain($domain,'primary');
                   9243:         push(@homeservers,&domain($domain,'primary'));
                   9244:     } else {
                   9245:         my %servers = &get_servers($domain,'library');
                   9246:         foreach my $tryserver (keys(%servers)) {
                   9247:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9248:                 push(@homeservers,$tryserver);
                   9249:             }
                   9250:         }
                   9251:     }
                   9252:     my $response;
                   9253:     foreach my $server (@homeservers) {
                   9254:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9255:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9256:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9257:             split(':',$response);
                   9258:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9259:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9260:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9261:             my ($name,$value)=split('=',$item);
                   9262:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9263:         }
                   9264:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9265:             my ($name,$value)=split('=',$item);
                   9266:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9267:         }
                   9268:         return 'ok';
                   9269:     }
                   9270:     return $response;
                   9271: }
1.792     raeburn  9272: 
1.1010    raeburn  9273: sub auto_courserequest_checks {
                   9274:     my ($dom) = @_;
1.1020    raeburn  9275:     my ($homeserver,%validations);
                   9276:     if ($dom =~ /^$match_domain$/) {
                   9277:         $homeserver = &domain($dom,'primary');
                   9278:     }
                   9279:     unless ($homeserver eq 'no_host') {
                   9280:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9281:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9282:             my @items = split(/&/,$response);
                   9283:             foreach my $item (@items) {
                   9284:                 my ($key,$value) = split('=',$item);
                   9285:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9286:             }
                   9287:         }
                   9288:     }
1.1010    raeburn  9289:     return %validations; 
                   9290: }
                   9291: 
1.1020    raeburn  9292: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9293:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9294:     my ($homeserver,$response);
                   9295:     if ($dom =~ /^$match_domain$/) {
                   9296:         $homeserver = &domain($dom,'primary');
                   9297:     }
1.1172.2.43  raeburn  9298:     unless ($homeserver eq 'no_host') {
                   9299:         my $customdata;
                   9300:         if (ref($custominfo) eq 'HASH') {
                   9301:             $customdata = &freeze_escape($custominfo);
                   9302:         }
1.1020    raeburn  9303:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9304:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9305:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9306:                                     $customdata,$homeserver));
1.1020    raeburn  9307:     }
                   9308:     return $response;
                   9309: }
                   9310: 
1.777     albertel 9311: sub auto_validate_class_sec {
1.918     raeburn  9312:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9313:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9314:     my $ownerlist;
                   9315:     if (ref($owners) eq 'ARRAY') {
                   9316:         $ownerlist = join(',',@{$owners});
                   9317:     } else {
                   9318:         $ownerlist = $owners;
                   9319:     }
1.773     raeburn  9320:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9321:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9322:     return $response;
                   9323: }
                   9324: 
1.1172.2.94  raeburn  9325: sub auto_validate_instclasses {
                   9326:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9327:     my ($homeserver,%validations);
                   9328:     $homeserver = &homeserver($cnum,$cdom);
                   9329:     unless ($homeserver eq 'no_host') {
                   9330:         my $ownerlist;
                   9331:         if (ref($owners) eq 'ARRAY') {
                   9332:             $ownerlist = join(',',@{$owners});
                   9333:         } else {
                   9334:             $ownerlist = $owners;
                   9335:         }
                   9336:         if (ref($classesref) eq 'HASH') {
                   9337:             my $classes = &freeze_escape($classesref);
                   9338:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9339:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9340:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9341:                 my @items = split(/&/,$response);
                   9342:                 foreach my $item (@items) {
                   9343:                     my ($key,$value) = split('=',$item);
                   9344:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9345:                 }
                   9346:             }
                   9347:         }
                   9348:     }
                   9349:     return %validations;
                   9350: }
                   9351: 
1.1172.2.38  raeburn  9352: sub auto_crsreq_update {
                   9353:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9354:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9355:     my ($homeserver,%crsreqresponse);
                   9356:     if ($cdom =~ /^$match_domain$/) {
                   9357:         $homeserver = &domain($cdom,'primary');
                   9358:     }
                   9359:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9360:         my $info;
                   9361:         if (ref($inbound) eq 'HASH') {
                   9362:             $info = &freeze_escape($inbound);
                   9363:         }
                   9364:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9365:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9366:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9367:                             &escape($title).':'.&escape($code).':'.
                   9368:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9369:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9370:             my @items = split(/&/,$response);
                   9371:             foreach my $item (@items) {
                   9372:                 my ($key,$value) = split('=',$item);
                   9373:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9374:             }
                   9375:         }
                   9376:     }
                   9377:     return \%crsreqresponse;
                   9378: }
                   9379: 
1.1172.2.78  raeburn  9380: sub auto_export_grades {
                   9381:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9382:     my ($homeserver,%exportresponse);
                   9383:     if ($cdom =~ /^$match_domain$/) {
                   9384:         $homeserver = &domain($cdom,'primary');
                   9385:     }
                   9386:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9387:         my $info;
                   9388:         if (ref($inforef) eq 'HASH') {
                   9389:             $info = &freeze_escape($inforef);
                   9390:         }
                   9391:         if (ref($gradesref) eq 'HASH') {
                   9392:             my $grades = &freeze_escape($gradesref);
                   9393:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9394:                                 $info.':'.$grades,$homeserver);
                   9395:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9396:                 my @items = split(/&/,$response);
                   9397:                 foreach my $item (@items) {
                   9398:                     my ($key,$value) = split('=',$item);
                   9399:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9400:                 }
                   9401:             }
                   9402:         }
                   9403:     }
                   9404:     return \%exportresponse;
                   9405: }
                   9406: 
1.1172.2.68  raeburn  9407: sub check_instcode_cloning {
                   9408:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9409:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9410:         return;
                   9411:     }
                   9412:     my $canclone;
                   9413:     if (@{$code_order} > 0) {
                   9414:         my $instcoderegexp ='^';
                   9415:         my @clonecodes = split(/\&/,$cloner);
                   9416:         foreach my $item (@{$code_order}) {
                   9417:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9418:                 foreach my $pair (@clonecodes) {
                   9419:                     my ($key,$val) = split(/\=/,$pair,2);
                   9420:                     $val = &unescape($val);
                   9421:                     if ($key eq $item) {
                   9422:                         $instcoderegexp .= '('.$val.')';
                   9423:                         last;
                   9424:                     }
                   9425:                 }
                   9426:             } else {
                   9427:                 $instcoderegexp .= $codedefaults->{$item};
                   9428:             }
                   9429:         }
                   9430:         $instcoderegexp .= '$';
                   9431:         my (@from,@to);
                   9432:         eval {
                   9433:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9434:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9435:         };
                   9436:         if ((@from > 0) && (@to > 0)) {
                   9437:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9438:             if (!@diffs) {
                   9439:                 $canclone = 1;
                   9440:             }
                   9441:         }
                   9442:     }
                   9443:     return $canclone;
                   9444: }
                   9445: 
                   9446: sub default_instcode_cloning {
                   9447:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9448:     my (%codedefaults,@code_order,$canclone);
                   9449:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9450:         %codedefaults = %{$codedefaultsref};
                   9451:         @code_order = @{$codeorderref};
                   9452:     } elsif ($clonedom) {
                   9453:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9454:     }
                   9455:     if (($domdefclone) && (@code_order)) {
                   9456:         my @clonecodes = split(/\+/,$domdefclone);
                   9457:         my $instcoderegexp ='^';
                   9458:         foreach my $item (@code_order) {
                   9459:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9460:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9461:             } else {
                   9462:                 $instcoderegexp .= $codedefaults{$item};
                   9463:             }
                   9464:         }
                   9465:         $instcoderegexp .= '$';
                   9466:         my (@from,@to);
                   9467:         eval {
                   9468:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9469:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9470:         };
                   9471:         if ((@from > 0) && (@to > 0)) {
                   9472:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9473:             if (!@diffs) {
                   9474:                 $canclone = 1;
                   9475:             }
                   9476:         }
                   9477:     }
                   9478:     return $canclone;
                   9479: }
                   9480: 
1.679     raeburn  9481: # ------------------------------------------------------- Course Group routines
                   9482: 
                   9483: sub get_coursegroups {
1.809     raeburn  9484:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9485:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9486: }
                   9487: 
1.679     raeburn  9488: sub modify_coursegroup {
                   9489:     my ($cdom,$cnum,$groupsettings) = @_;
                   9490:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9491: }
                   9492: 
1.809     raeburn  9493: sub toggle_coursegroup_status {
                   9494:     my ($cdom,$cnum,$group,$action) = @_;
                   9495:     my ($from_namespace,$to_namespace);
                   9496:     if ($action eq 'delete') {
                   9497:         $from_namespace = 'coursegroups';
                   9498:         $to_namespace = 'deleted_groups';
                   9499:     } else {
                   9500:         $from_namespace = 'deleted_groups';
                   9501:         $to_namespace = 'coursegroups';
                   9502:     }
                   9503:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9504:     if (my $tmp = &error(%curr_group)) {
                   9505:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9506:         return ('read error',$tmp);
                   9507:     } else {
                   9508:         my %savedsettings = %curr_group; 
1.809     raeburn  9509:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9510:         my $deloutcome;
                   9511:         if ($result eq 'ok') {
1.809     raeburn  9512:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9513:         } else {
                   9514:             return ('write error',$result);
                   9515:         }
                   9516:         if ($deloutcome eq 'ok') {
                   9517:             return 'ok';
                   9518:         } else {
                   9519:             return ('delete error',$deloutcome);
                   9520:         }
                   9521:     }
                   9522: }
                   9523: 
1.679     raeburn  9524: sub modify_group_roles {
1.957     raeburn  9525:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9526:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9527:     my $role = 'gr/'.&escape($userprivs);
                   9528:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9529:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9530:     if ($result eq 'ok') {
                   9531:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9532:     }
1.679     raeburn  9533:     return $result;
                   9534: }
                   9535: 
                   9536: sub modify_coursegroup_membership {
                   9537:     my ($cdom,$cnum,$membership) = @_;
                   9538:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9539:     return $result;
                   9540: }
                   9541: 
1.682     raeburn  9542: sub get_active_groups {
                   9543:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9544:     my $now = time;
                   9545:     my %groups = ();
                   9546:     foreach my $key (keys(%env)) {
1.811     albertel 9547:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9548:             my ($start,$end) = split(/\./,$env{$key});
                   9549:             if (($end!=0) && ($end<$now)) { next; }
                   9550:             if (($start!=0) && ($start>$now)) { next; }
                   9551:             if ($1 eq $cdom && $2 eq $cnum) {
                   9552:                 $groups{$3} = $env{$key} ;
                   9553:             }
                   9554:         }
                   9555:     }
                   9556:     return %groups;
                   9557: }
                   9558: 
1.683     raeburn  9559: sub get_group_membership {
                   9560:     my ($cdom,$cnum,$group) = @_;
                   9561:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9562: }
                   9563: 
                   9564: sub get_users_groups {
                   9565:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9566:     my @usersgroups;
1.683     raeburn  9567:     my $cachetime=1800;
                   9568: 
                   9569:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9570:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9571:     if (defined($cached)) {
1.734     albertel 9572:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9573:     } else {  
                   9574:         $grouplist = '';
1.816     raeburn  9575:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9576:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9577:         my $access_end = $env{'course.'.$courseid.
                   9578:                               '.default_enrollment_end_date'};
                   9579:         my $now = time;
                   9580:         foreach my $key (keys(%roleshash)) {
                   9581:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9582:                 my $group = $1;
                   9583:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9584:                     my $start = $2;
                   9585:                     my $end = $1;
                   9586:                     if ($start == -1) { next; } # deleted from group
                   9587:                     if (($start!=0) && ($start>$now)) { next; }
                   9588:                     if (($end!=0) && ($end<$now)) {
                   9589:                         if ($access_end && $access_end < $now) {
                   9590:                             if ($access_end - $end < 86400) {
                   9591:                                 push(@usersgroups,$group);
1.733     raeburn  9592:                             }
                   9593:                         }
1.817     raeburn  9594:                         next;
1.733     raeburn  9595:                     }
1.817     raeburn  9596:                     push(@usersgroups,$group);
1.683     raeburn  9597:                 }
                   9598:             }
                   9599:         }
1.817     raeburn  9600:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9601:         $grouplist = join(':',@usersgroups);
                   9602:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9603:     }
1.733     raeburn  9604:     return @usersgroups;
1.683     raeburn  9605: }
                   9606: 
                   9607: sub devalidate_getgroups_cache {
                   9608:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9609:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9610: 
1.683     raeburn  9611:     my $hashid="$udom:$uname:$courseid";
                   9612:     &devalidate_cache_new('getgroups',$hashid);
                   9613: }
                   9614: 
1.12      www      9615: # ------------------------------------------------------------------ Plain Text
                   9616: 
                   9617: sub plaintext {
1.988     raeburn  9618:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9619:     if ($short =~ m{^cr/}) {
1.758     albertel 9620: 	return (split('/',$short))[-1];
                   9621:     }
1.742     raeburn  9622:     if (!defined($cid)) {
                   9623:         $cid = $env{'request.course.id'};
                   9624:     }
                   9625:     my %rolenames = (
1.1008    raeburn  9626:                       Course    => 'std',
                   9627:                       Community => 'alt1',
1.742     raeburn  9628:                     );
1.1037    raeburn  9629:     if ($cid ne '') {
                   9630:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9631:             unless ($forcedefault) {
                   9632:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9633:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9634:                 return &Apache::lonlocal::mt($roletext);
                   9635:             }
                   9636:         }
                   9637:     }
                   9638:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9639:         (defined($rolenames{$type})) && 
                   9640:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9641:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9642:     } elsif ($cid ne '') {
                   9643:         my $crstype = $env{'course.'.$cid.'.type'};
                   9644:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9645:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9646:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9647:         }
1.742     raeburn  9648:     }
1.1037    raeburn  9649:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9650: }
                   9651: 
                   9652: # ----------------------------------------------------------------- Assign Role
                   9653: 
                   9654: sub assignrole {
1.957     raeburn  9655:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9656:         $context)=@_;
1.21      www      9657:     my $mrole;
                   9658:     if ($role =~ /^cr\//) {
1.393     www      9659:         my $cwosec=$url;
1.811     albertel 9660:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9661: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9662:            my $refused = 1;
                   9663:            if ($context eq 'requestcourses') {
                   9664:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9665:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9666:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9667:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9668:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9669:                            if ($crsenv{'internal.courseowner'} eq
                   9670:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9671:                                $refused = '';
                   9672:                            }
                   9673:                        }
                   9674:                    }
                   9675:                }
                   9676:            }
                   9677:            if ($refused) {
                   9678:                &logthis('Refused custom assignrole: '.
                   9679:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9680:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9681:                return 'refused';
                   9682:            }
1.104     www      9683:         }
1.21      www      9684:         $mrole='cr';
1.678     raeburn  9685:     } elsif ($role =~ /^gr\//) {
                   9686:         my $cwogrp=$url;
1.811     albertel 9687:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9688:         unless (&allowed('mdg',$cwogrp)) {
                   9689:             &logthis('Refused group assignrole: '.
                   9690:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9691:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9692:             return 'refused';
                   9693:         }
                   9694:         $mrole='gr';
1.21      www      9695:     } else {
1.82      www      9696:         my $cwosec=$url;
1.811     albertel 9697:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9698:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9699:             my $refused;
                   9700:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9701:                 if (!(&allowed('c'.$role,$url))) {
                   9702:                     $refused = 1;
                   9703:                 }
                   9704:             } else {
                   9705:                 $refused = 1;
                   9706:             }
1.947     raeburn  9707:             if ($refused) {
1.1045    raeburn  9708:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9709:                 if (!$selfenroll && $context eq 'course') {
                   9710:                     my %crsenv;
                   9711:                     if ($role eq 'cc' || $role eq 'co') {
                   9712:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9713:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9714:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9715:                                 if ($crsenv{'internal.courseowner'} eq 
                   9716:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9717:                                     $refused = '';
                   9718:                                 }
                   9719:                             }
                   9720:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9721:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9722:                                 if ($crsenv{'internal.courseowner'} eq 
                   9723:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9724:                                     $refused = '';
                   9725:                                 }
                   9726:                             }
                   9727:                         }
                   9728:                     }
                   9729:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9730:                     $refused = '';
1.1017    raeburn  9731:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9732:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9733:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9734:                         my $wrongcc;
                   9735:                         if ($cnum =~ /^$match_community$/) {
                   9736:                             $wrongcc = 1 if ($role eq 'cc');
                   9737:                         } else {
                   9738:                             $wrongcc = 1 if ($role eq 'co');
                   9739:                         }
                   9740:                         unless ($wrongcc) {
                   9741:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9742:                             if ($crsenv{'internal.courseowner'} eq 
                   9743:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9744:                                 $refused = '';
                   9745:                             }
1.1017    raeburn  9746:                         }
                   9747:                     }
1.1172.2.9  raeburn  9748:                 } elsif ($context eq 'requestauthor') {
                   9749:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9750:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9751:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9752:                             $refused = '';
                   9753:                         } else {
                   9754:                             my %domdefaults = &get_domain_defaults($udom);
                   9755:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9756:                                 my $checkbystatus;
                   9757:                                 if ($env{'user.adv'}) {
                   9758:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9759:                                     if ($disposition eq 'automatic') {
                   9760:                                         $refused = '';
                   9761:                                     } elsif ($disposition eq '') {
                   9762:                                         $checkbystatus = 1;
                   9763:                                     }
                   9764:                                 } else {
                   9765:                                     $checkbystatus = 1;
                   9766:                                 }
                   9767:                                 if ($checkbystatus) {
                   9768:                                     if ($env{'environment.inststatus'}) {
                   9769:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9770:                                         foreach my $type (@inststatuses) {
                   9771:                                             if (($type ne '') &&
                   9772:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9773:                                                 $refused = '';
                   9774:                                             }
                   9775:                                         }
                   9776:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9777:                                         $refused = '';
                   9778:                                     }
                   9779:                                 }
                   9780:                             }
                   9781:                         }
                   9782:                     }
1.1017    raeburn  9783:                 }
                   9784:                 if ($refused) {
1.947     raeburn  9785:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9786:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9787: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9788:                     return 'refused';
                   9789:                 }
1.932     raeburn  9790:             }
1.1131    raeburn  9791:         } elsif ($role eq 'au') {
                   9792:             if ($url ne '/'.$udom.'/') {
                   9793:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9794:                          ' to assign author role for '.$uname.':'.$udom.
                   9795:                          ' in domain: '.$url.' refused (wrong domain).');
                   9796:                 return 'refused';
                   9797:             }
1.104     www      9798:         }
1.21      www      9799:         $mrole=$role;
                   9800:     }
1.620     albertel 9801:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9802:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9803:     if ($end) { $command.='_'.$end; }
1.21      www      9804:     if ($start) {
                   9805: 	if ($end) { 
1.81      www      9806:            $command.='_'.$start; 
1.21      www      9807:         } else {
1.81      www      9808:            $command.='_0_'.$start;
1.21      www      9809:         }
                   9810:     }
1.739     raeburn  9811:     my $origstart = $start;
                   9812:     my $origend = $end;
1.957     raeburn  9813:     my $delflag;
1.357     www      9814: # actually delete
                   9815:     if ($deleteflag) {
1.373     www      9816: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9817: # modify command to delete the role
1.620     albertel 9818:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9819:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9820: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9821: # set start and finish to negative values for userrolelog
                   9822:            $start=-1;
                   9823:            $end=-1;
1.957     raeburn  9824:            $delflag = 1;
1.357     www      9825:         }
                   9826:     }
                   9827: # send command
1.349     www      9828:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9829: # log new user role if status is ok
1.349     www      9830:     if ($answer eq 'ok') {
1.663     raeburn  9831: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9832:         if (($role eq 'cc') || ($role eq 'in') ||
                   9833:             ($role eq 'ep') || ($role eq 'ad') ||
                   9834:             ($role eq 'ta') || ($role eq 'st') ||
                   9835:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9836:             ($role eq 'co')) {
1.1172.2.13  raeburn  9837: # for course roles, perform group memberships changes triggered by role change.
                   9838:             unless ($role =~ /^gr/) {
                   9839:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9840:                                                  $origstart,$selfenroll,$context);
                   9841:             }
1.1172.2.9  raeburn  9842:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9843:                            $selfenroll,$context);
                   9844:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9845:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9846:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9847:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9848:                            $context);
                   9849:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9850:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9851:                              $context);
                   9852:         }
1.1053    raeburn  9853:         if ($role eq 'cc') {
                   9854:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9855:         }
1.349     www      9856:     }
                   9857:     return $answer;
1.169     harris41 9858: }
                   9859: 
1.1053    raeburn  9860: sub autoupdate_coowners {
                   9861:     my ($url,$end,$start,$uname,$udom) = @_;
                   9862:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9863:     if (($cdom ne '') && ($cnum ne '')) {
                   9864:         my $now = time;
                   9865:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9866:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9867:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9868:             my $instcode = $coursehash{'internal.coursecode'};
                   9869:             if ($instcode ne '') {
1.1056    raeburn  9870:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9871:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9872:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9873:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9874:                         if ($result eq 'valid') {
                   9875:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9876:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9877:                                     push(@newcoowners,$coowner);
                   9878:                                 }
                   9879:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9880:                                     push(@newcoowners,$uname.':'.$udom);
                   9881:                                 }
                   9882:                                 @newcoowners = sort(@newcoowners);
                   9883:                             } else {
                   9884:                                 push(@newcoowners,$uname.':'.$udom);
                   9885:                             }
                   9886:                         } else {
                   9887:                             if ($coursehash{'internal.co-owners'}) {
                   9888:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9889:                                     unless ($coowner eq $uname.':'.$udom) {
                   9890:                                         push(@newcoowners,$coowner);
                   9891:                                     }
                   9892:                                 }
                   9893:                                 unless (@newcoowners > 0) {
                   9894:                                     $delcoowners = 1;
                   9895:                                     $coowners = '';
                   9896:                                 }
                   9897:                             }
                   9898:                         }
                   9899:                         if (@newcoowners || $delcoowners) {
                   9900:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9901:                                             $delcoowners,@newcoowners);
                   9902:                         }
                   9903:                     }
                   9904:                 }
                   9905:             }
                   9906:         }
                   9907:     }
                   9908: }
                   9909: 
                   9910: sub store_coowners {
                   9911:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9912:     my $cid = $cdom.'_'.$cnum;
                   9913:     my ($coowners,$delresult,$putresult);
                   9914:     if (@newcoowners) {
                   9915:         $coowners = join(',',@newcoowners);
                   9916:         my %coownershash = (
                   9917:                             'internal.co-owners' => $coowners,
                   9918:                            );
                   9919:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9920:         if ($putresult eq 'ok') {
                   9921:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9922:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9923:             }
                   9924:         }
                   9925:     }
                   9926:     if ($delcoowners) {
                   9927:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9928:         if ($delresult eq 'ok') {
                   9929:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9930:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9931:             }
                   9932:         }
                   9933:     }
                   9934:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9935:         my %crsinfo =
                   9936:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9937:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9938:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9939:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9940:         }
                   9941:     }
                   9942: }
                   9943: 
1.169     harris41 9944: # -------------------------------------------------- Modify user authentication
1.197     www      9945: # Overrides without validation
                   9946: 
1.169     harris41 9947: sub modifyuserauth {
                   9948:     my ($udom,$uname,$umode,$upass)=@_;
                   9949:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9950:     my $allowed;
                   9951:     if (&allowed('mau',$udom)) {
                   9952:         $allowed = 1;
                   9953:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9954:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9955:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9956:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9957:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9958:         if (($cdom ne '') && ($cnum ne '')) {
                   9959:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9960:             if ($is_owner) {
                   9961:                 $allowed = 1;
                   9962:             }
                   9963:         }
                   9964:     }
                   9965:     unless ($allowed) { return 'refused'; }
1.197     www      9966:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9967:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9968:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9969:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9970: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  9971:     my $ip = &get_requestor_ip();
1.620     albertel 9972:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9973:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  9974:          '(Remote '.$ip.'): '.$reply);
1.197     www      9975:     &log($udom,,$uname,$uhome,
1.620     albertel 9976:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9977:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  9978:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 9979:     unless ($reply eq 'ok') {
1.197     www      9980:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9981: 	return 'error: '.$reply;
                   9982:     }   
1.170     harris41 9983:     return 'ok';
1.80      www      9984: }
                   9985: 
1.81      www      9986: # --------------------------------------------------------------- Modify a user
1.80      www      9987: 
1.81      www      9988: sub modifyuser {
1.206     matthew  9989:     my ($udom,    $uname, $uid,
                   9990:         $umode,   $upass, $first,
                   9991:         $middle,  $last,  $gene,
1.1058    raeburn  9992:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9993:     $udom= &LONCAPA::clean_domain($udom);
                   9994:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9995:     my $showcandelete = 'none';
                   9996:     if (ref($candelete) eq 'ARRAY') {
                   9997:         if (@{$candelete} > 0) {
                   9998:             $showcandelete = join(', ',@{$candelete});
                   9999:         }
                   10000:     }
1.81      www      10001:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10002:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10003: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10004:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10005:                                      ' desiredhome not specified'). 
1.620     albertel 10006:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10007:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10008:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10009:     my $newuser;
                   10010:     if ($uhome eq 'no_host') {
                   10011:         $newuser = 1;
                   10012:     }
1.80      www      10013: # ----------------------------------------------------------------- Create User
1.406     albertel 10014:     if (($uhome eq 'no_host') && 
                   10015: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10016:         my $unhome='';
1.844     albertel 10017:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10018:             $unhome = $desiredhome;
1.620     albertel 10019: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10020: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10021:         } else { # load balancing routine for determining $unhome
1.81      www      10022:             my $loadm=10000000;
1.841     albertel 10023: 	    my %servers = &get_servers($udom,'library');
                   10024: 	    foreach my $tryserver (keys(%servers)) {
                   10025: 		my $answer=reply('load',$tryserver);
                   10026: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10027: 		    $loadm=$answer;
                   10028: 		    $unhome=$tryserver;
                   10029: 		}
1.80      www      10030: 	    }
                   10031:         }
                   10032:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10033: 	    return 'error: unable to find a home server for '.$uname.
                   10034:                    ' in domain '.$udom;
1.80      www      10035:         }
                   10036:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10037:                          &escape($upass),$unhome);
                   10038: 	unless ($reply eq 'ok') {
                   10039:             return 'error: '.$reply;
                   10040:         }   
1.230     stredwic 10041:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10042:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10043: 	    return 'error: unable verify users home machine.';
1.80      www      10044:         }
1.209     matthew  10045:     }   # End of creation of new user
1.80      www      10046: # ---------------------------------------------------------------------- Add ID
                   10047:     if ($uid) {
                   10048:        $uid=~tr/A-Z/a-z/;
                   10049:        my %uidhash=&idrget($udom,$uname);
1.196     www      10050:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10051:          && (!$forceid)) {
1.80      www      10052: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10053: 	      return 'error: user id "'.$uid.'" does not match '.
                   10054:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10055:           }
                   10056:        } else {
                   10057: 	  &idput($udom,($uname => $uid));
                   10058:        }
                   10059:     }
                   10060: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10061:     my @tmp=&get('environment',
1.899     raeburn  10062: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10063:                     'permanentemail','inststatus'],
1.134     albertel 10064: 		   $udom,$uname);
1.1075    raeburn  10065:     my (%names,%oldnames);
1.313     matthew  10066:     if ($tmp[0] =~ m/^error:.*/) { 
                   10067:         %names=(); 
                   10068:     } else {
                   10069:         %names = @tmp;
1.1075    raeburn  10070:         %oldnames = %names;
1.313     matthew  10071:     }
1.388     www      10072: #
1.1058    raeburn  10073: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10074: # of users did not contain them), do not overwrite existing values
                   10075: # unless field is in $candelete array ref.  
                   10076: #
                   10077: 
                   10078:     my @fields = ('firstname','middlename','lastname','generation',
                   10079:                   'permanentemail','id');
                   10080:     my %newvalues;
                   10081:     if (ref($candelete) eq 'ARRAY') {
                   10082:         foreach my $field (@fields) {
                   10083:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10084:                 if ($field eq 'firstname') {
                   10085:                     $names{$field} = $first;
                   10086:                 } elsif ($field eq 'middlename') {
                   10087:                     $names{$field} = $middle;
                   10088:                 } elsif ($field eq 'lastname') {
                   10089:                     $names{$field} = $last;
                   10090:                 } elsif ($field eq 'generation') { 
                   10091:                     $names{$field} = $gene;
                   10092:                 } elsif ($field eq 'permanentemail') {
                   10093:                     $names{$field} = $email;
                   10094:                 } elsif ($field eq 'id') {
                   10095:                     $names{$field}  = $uid;
                   10096:                 }
                   10097:             }
                   10098:         }
                   10099:     }
1.388     www      10100:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10101:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10102:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10103:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10104:     if ($email) {
                   10105:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10106:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10107:     }
1.899     raeburn  10108:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10109:     if (defined($inststatus)) {
                   10110:         $names{'inststatus'} = '';
                   10111:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10112:         if (ref($usertypes) eq 'HASH') {
                   10113:             my @okstatuses; 
                   10114:             foreach my $item (split(/:/,$inststatus)) {
                   10115:                 if (defined($usertypes->{$item})) {
                   10116:                     push(@okstatuses,$item);  
                   10117:                 }
                   10118:             }
                   10119:             if (@okstatuses) {
                   10120:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10121:             }
                   10122:         }
                   10123:     }
1.1075    raeburn  10124:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10125:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10126:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10127:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10128:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10129:     } else {
                   10130:         $logmsg .= ' during self creation';
                   10131:     }
1.1075    raeburn  10132:     my $changed;
                   10133:     if ($newuser) {
                   10134:         $changed = 1;
                   10135:     } else {
                   10136:         foreach my $field (@fields) {
                   10137:             if ($names{$field} ne $oldnames{$field}) {
                   10138:                 $changed = 1;
                   10139:                 last;
                   10140:             }
                   10141:         }
                   10142:     }
                   10143:     unless ($changed) {
                   10144:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10145:         &logthis($logmsg);
                   10146:         return 'ok';
                   10147:     }
                   10148:     my $reply = &put('environment', \%names, $udom,$uname);
                   10149:     if ($reply ne 'ok') { 
                   10150:         return 'error: '.$reply;
                   10151:     }
1.1087    raeburn  10152:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10153:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10154:     }
1.1075    raeburn  10155:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10156:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10157:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10158:     &logthis($logmsg);
1.134     albertel 10159:     return 'ok';
1.80      www      10160: }
                   10161: 
1.81      www      10162: # -------------------------------------------------------------- Modify student
1.80      www      10163: 
1.81      www      10164: sub modifystudent {
                   10165:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10166:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10167:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10168:     if (!$cid) {
1.620     albertel 10169: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10170: 	    return 'not_in_class';
                   10171: 	}
1.80      www      10172:     }
                   10173: # --------------------------------------------------------------- Make the user
1.81      www      10174:     my $reply=&modifyuser
1.209     matthew  10175: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10176:          $desiredhome,$email,$inststatus);
1.80      www      10177:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10178:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10179:     # student's environment
1.297     matthew  10180:     $uid = undef if (!$forceid);
1.455     albertel 10181:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10182: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10183:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10184:     return $reply;
                   10185: }
                   10186: 
                   10187: sub modify_student_enrollment {
1.1172.2.23  raeburn  10188:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10189:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10190:     my ($cdom,$cnum,$chome);
                   10191:     if (!$cid) {
1.620     albertel 10192: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10193: 	    return 'not_in_class';
                   10194: 	}
1.620     albertel 10195: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10196: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10197:     } else {
                   10198: 	($cdom,$cnum)=split(/_/,$cid);
                   10199:     }
1.620     albertel 10200:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10201:     if (!$chome) {
1.457     raeburn  10202: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10203:     }
1.455     albertel 10204:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10205:     # Make sure the user exists
1.81      www      10206:     my $uhome=&homeserver($uname,$udom);
                   10207:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10208: 	return 'error: no such user';
                   10209:     }
1.297     matthew  10210:     # Get student data if we were not given enough information
                   10211:     if (!defined($first)  || $first  eq '' || 
                   10212:         !defined($last)   || $last   eq '' || 
                   10213:         !defined($uid)    || $uid    eq '' || 
                   10214:         !defined($middle) || $middle eq '' || 
                   10215:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10216:         # They did not supply us with enough data to enroll the student, so
                   10217:         # we need to pick up more information.
1.297     matthew  10218:         my %tmp = &get('environment',
1.294     matthew  10219:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10220:                        ,$udom,$uname);
                   10221: 
1.800     albertel 10222:         #foreach my $key (keys(%tmp)) {
                   10223:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10224:         #}
1.294     matthew  10225:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10226:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10227:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10228:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10229:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10230:     }
1.556     albertel 10231:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10232:     my $user = "$uname:$udom";
                   10233:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10234:     my $reply=cput('classlist',
1.1148    raeburn  10235: 		   {$user => 
1.1172.2.76  raeburn  10236: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10237: 		   $cdom,$cnum);
1.1148    raeburn  10238:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10239:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10240:     } else { 
1.81      www      10241: 	return 'error: '.$reply;
                   10242:     }
1.297     matthew  10243:     # Add student role to user
1.83      www      10244:     my $uurl='/'.$cid;
1.81      www      10245:     $uurl=~s/\_/\//g;
                   10246:     if ($usec) {
                   10247: 	$uurl.='/'.$usec;
                   10248:     }
1.1148    raeburn  10249:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10250:                              $selfenroll,$context);
                   10251:     if ($result ne 'ok') {
                   10252:         if ($old_entry{$user} ne '') {
                   10253:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10254:         } else {
                   10255:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10256:         }
                   10257:     }
                   10258:     return $result; 
1.21      www      10259: }
                   10260: 
1.556     albertel 10261: sub format_name {
                   10262:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10263:     my $name;
                   10264:     if ($first ne 'lastname') {
                   10265: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10266:     } else {
                   10267: 	if ($lastname=~/\S/) {
                   10268: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10269: 	    $name=~s/\s+,/,/;
                   10270: 	} else {
                   10271: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10272: 	}
                   10273:     }
                   10274:     $name=~s/^\s+//;
                   10275:     $name=~s/\s+$//;
                   10276:     $name=~s/\s+/ /g;
                   10277:     return $name;
                   10278: }
                   10279: 
1.84      www      10280: # ------------------------------------------------- Write to course preferences
                   10281: 
                   10282: sub writecoursepref {
                   10283:     my ($courseid,%prefs)=@_;
                   10284:     $courseid=~s/^\///;
                   10285:     $courseid=~s/\_/\//g;
                   10286:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10287:     my $chome=homeserver($cnum,$cdomain);
                   10288:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10289: 	return 'error: no such course';
                   10290:     }
                   10291:     my $cstring='';
1.800     albertel 10292:     foreach my $pref (keys(%prefs)) {
                   10293: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10294:     }
1.84      www      10295:     $cstring=~s/\&$//;
                   10296:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10297: }
                   10298: 
                   10299: # ---------------------------------------------------------- Make/modify course
                   10300: 
                   10301: sub createcourse {
1.741     raeburn  10302:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10303:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10304:     $url=&declutter($url);
                   10305:     my $cid='';
1.1028    raeburn  10306:     if ($context eq 'requestcourses') {
                   10307:         my $can_create = 0;
                   10308:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10309:         if ($udom eq $ownerdom) {
                   10310:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10311:                                   $context)) {
                   10312:                 $can_create = 1;
                   10313:             }
                   10314:         } else {
                   10315:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10316:                                            $category);
                   10317:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10318:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10319:                 if (@curr > 0) {
                   10320:                     my @options = qw(approval validate autolimit);
                   10321:                     my $optregex = join('|',@options);
                   10322:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10323:                         $can_create = 1;
                   10324:                     }
                   10325:                 }
                   10326:             }
                   10327:         }
                   10328:         if ($can_create) {
                   10329:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10330:                 unless (&allowed('ccc',$udom)) {
                   10331:                     return 'refused'; 
                   10332:                 }
1.1017    raeburn  10333:             }
                   10334:         } else {
                   10335:             return 'refused';
                   10336:         }
1.1028    raeburn  10337:     } elsif (!&allowed('ccc',$udom)) {
                   10338:         return 'refused';
1.84      www      10339:     }
1.1011    raeburn  10340: # --------------------------------------------------------------- Get Unique ID
                   10341:     my $uname;
                   10342:     if ($cnum =~ /^$match_courseid$/) {
                   10343:         my $chome=&homeserver($cnum,$udom,'true');
                   10344:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10345:             $uname = $cnum;
                   10346:         } else {
1.1038    raeburn  10347:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10348:         }
                   10349:     } else {
1.1038    raeburn  10350:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10351:     }
                   10352:     return $uname if ($uname =~ /^error/);
                   10353: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10354:     if (!defined($course_server)) {
                   10355:         if (defined(&domain($udom,'primary'))) {
                   10356:             $course_server = &domain($udom,'primary');
                   10357:         } else {
                   10358:             $course_server = $env{'user.home'}; 
                   10359:         }
                   10360:     }
                   10361:     my %host_servers =
                   10362:         &Apache::lonnet::get_servers($udom,'library');
                   10363:     unless ($host_servers{$course_server}) {
                   10364:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10365:     }
1.84      www      10366: # ------------------------------------------------------------- Make the course
                   10367:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10368:                       $course_server);
1.84      www      10369:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10370:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10371:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10372: 	return 'error: no such course';
                   10373:     }
1.271     www      10374: # ----------------------------------------------------------------- Course made
1.516     raeburn  10375: # log existence
1.1029    raeburn  10376:     my $now = time;
1.918     raeburn  10377:     my $newcourse = {
                   10378:                     $udom.'_'.$uname => {
1.921     raeburn  10379:                                      description => $description,
                   10380:                                      inst_code   => $inst_code,
                   10381:                                      owner       => $course_owner,
                   10382:                                      type        => $crstype,
1.1029    raeburn  10383:                                      creator     => $env{'user.name'}.':'.
                   10384:                                                     $env{'user.domain'},
                   10385:                                      created     => $now,
                   10386:                                      context     => $context,
1.918     raeburn  10387:                                                 },
                   10388:                     };
1.921     raeburn  10389:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10390: # set toplevel url
1.271     www      10391:     my $topurl=$url;
                   10392:     unless ($nonstandard) {
                   10393: # ------------------------------------------ For standard courses, make top url
                   10394:         my $mapurl=&clutter($url);
1.278     www      10395:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10396:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10397: <map>
                   10398: <resource id="1" type="start"></resource>
                   10399: <resource id="2" src="$mapurl"></resource>
                   10400: <resource id="3" type="finish"></resource>
                   10401: <link index="1" from="1" to="2"></link>
                   10402: <link index="2" from="2" to="3"></link>
                   10403: </map>
                   10404: ENDINITMAP
                   10405:         $topurl=&declutter(
1.638     albertel 10406:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10407:                           );
                   10408:     }
                   10409: # ----------------------------------------------------------- Write preferences
1.84      www      10410:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10411:                      ('description'              => $description,
                   10412:                       'url'                      => $topurl,
                   10413:                       'internal.creator'         => $env{'user.name'}.':'.
                   10414:                                                     $env{'user.domain'},
                   10415:                       'internal.created'         => $now,
                   10416:                       'internal.creationcontext' => $context)
                   10417:                     );
1.84      www      10418:     return '/'.$udom.'/'.$uname;
                   10419: }
                   10420: 
1.1011    raeburn  10421: # ------------------------------------------------------------------- Create ID
                   10422: sub generate_coursenum {
1.1038    raeburn  10423:     my ($udom,$crstype) = @_;
1.1011    raeburn  10424:     my $domdesc = &domain($udom);
                   10425:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10426:     my $first;
                   10427:     if ($crstype eq 'Community') {
                   10428:         $first = '0';
                   10429:     } else {
                   10430:         $first = int(1+rand(9)); 
                   10431:     } 
                   10432:     my $uname=$first.
1.1011    raeburn  10433:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10434:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10435:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10436: # ----------------------------------------------- Make sure that does not exist
                   10437:     my $uhome=&homeserver($uname,$udom,'true');
                   10438:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10439:         if ($crstype eq 'Community') {
                   10440:             $first = '0';
                   10441:         } else {
                   10442:             $first = int(1+rand(9));
                   10443:         }
                   10444:         $uname=$first.
1.1011    raeburn  10445:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10446:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10447:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10448:         $uhome=&homeserver($uname,$udom,'true');
                   10449:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10450:             return 'error: unable to generate unique course-ID';
                   10451:         }
                   10452:     }
                   10453:     return $uname;
                   10454: }
                   10455: 
1.813     albertel 10456: sub is_course {
1.1167    droeschl 10457:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10458:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10459:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10460:     my $uhome=&homeserver($cnum,$cdom);
                   10461:     my $iscourse;
                   10462:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10463:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10464:     } else {
                   10465:         my $hashid = $cdom.':'.$cnum;
                   10466:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10467:         unless (defined($cached)) {
                   10468:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10469:                                         $cnum,undef,undef,'.');
                   10470:             $iscourse = 0;
                   10471:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10472:                 $iscourse = 1;
                   10473:             }
                   10474:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10475:         }
                   10476:     }
                   10477:     return unless($iscourse);
1.1167    droeschl 10478:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10479: }
                   10480: 
1.1015    raeburn  10481: sub store_userdata {
                   10482:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10483:     my $result;
1.1016    raeburn  10484:     if ($datakey ne '') {
1.1013    raeburn  10485:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10486:             if ($udom eq '' || $uname eq '') {
                   10487:                 $udom = $env{'user.domain'};
                   10488:                 $uname = $env{'user.name'};
                   10489:             }
                   10490:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10491:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10492:                 $result = 'error: no_host';
                   10493:             } else {
1.1172.2.138  raeburn  10494:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10495:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10496: 
                   10497:                 my $namevalue='';
                   10498:                 foreach my $key (keys(%{$storehash})) {
                   10499:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10500:                 }
                   10501:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10502:                 unless ($namespace eq 'courserequests') {
                   10503:                     $datakey = &escape($datakey);
                   10504:                 }
1.1105    raeburn  10505:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10506:                                   $namevalue,$uhome);
1.1013    raeburn  10507:             }
                   10508:         } else {
                   10509:             $result = 'error: data to store was not a hash reference'; 
                   10510:         }
                   10511:     } else {
                   10512:         $result= 'error: invalid requestkey'; 
                   10513:     }
                   10514:     return $result;
                   10515: }
                   10516: 
1.21      www      10517: # ---------------------------------------------------------- Assign Custom Role
                   10518: 
                   10519: sub assigncustomrole {
1.957     raeburn  10520:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10521:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10522:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10523: }
                   10524: 
                   10525: # ----------------------------------------------------------------- Revoke Role
                   10526: 
                   10527: sub revokerole {
1.957     raeburn  10528:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10529:     my $now=time;
1.965     raeburn  10530:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10531: }
                   10532: 
                   10533: # ---------------------------------------------------------- Revoke Custom Role
                   10534: 
                   10535: sub revokecustomrole {
1.957     raeburn  10536:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10537:     my $now=time;
1.357     www      10538:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10539:            $deleteflag,$selfenroll,$context);
1.17      www      10540: }
                   10541: 
1.533     banghart 10542: # ------------------------------------------------------------ Disk usage
1.535     albertel 10543: sub diskusage {
1.955     raeburn  10544:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10545:     $directorypath =~ s/\/$//;
                   10546:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10547:                        .&escape($getpropath).':'.&escape($uname).':'
                   10548:                        .&escape($udom),homeserver($uname,$udom));
                   10549:     if ($listing eq 'unknown_cmd') {
                   10550:         if ($getpropath) {
                   10551:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10552:         }
                   10553:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10554:     }
1.514     albertel 10555:     return $listing;
1.512     banghart 10556: }
                   10557: 
1.566     banghart 10558: sub is_locked {
1.1096    raeburn  10559:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10560:     my @check;
                   10561:     my $is_locked;
1.1093    raeburn  10562:     push (@check,$file_name);
1.613     albertel 10563:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10564: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10565:     my ($tmp)=keys(%locked);
                   10566:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10567:     
1.566     banghart 10568:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10569:         $is_locked = 'false';
                   10570:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10571:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10572:                $is_locked = 'true';
1.1096    raeburn  10573:                if (ref($which) eq 'ARRAY') {
                   10574:                    push(@{$which},$entry);
                   10575:                } else {
                   10576:                    last;
                   10577:                }
1.745     raeburn  10578:            }
                   10579:        }
1.566     banghart 10580:     } else {
                   10581:         $is_locked = 'false';
                   10582:     }
1.1093    raeburn  10583:     return $is_locked;
1.566     banghart 10584: }
                   10585: 
1.759     albertel 10586: sub declutter_portfile {
                   10587:     my ($file) = @_;
1.833     albertel 10588:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10589:     return $file;
                   10590: }
                   10591: 
1.559     banghart 10592: # ------------------------------------------------------------- Mark as Read Only
                   10593: 
                   10594: sub mark_as_readonly {
                   10595:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10596:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10597:     my ($tmp)=keys(%current_permissions);
                   10598:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10599:     foreach my $file (@{$files}) {
1.759     albertel 10600: 	$file = &declutter_portfile($file);
1.561     banghart 10601:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10602:     }
1.613     albertel 10603:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10604:     return;
                   10605: }
                   10606: 
1.572     banghart 10607: # ------------------------------------------------------------Save Selected Files
                   10608: 
                   10609: sub save_selected_files {
                   10610:     my ($user, $path, @files) = @_;
                   10611:     my $filename = $user."savedfiles";
1.573     banghart 10612:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10613:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10614:     foreach my $file (@files) {
1.620     albertel 10615:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10616:     }
                   10617:     foreach my $file (@other_files) {
1.574     banghart 10618:         print (OUT $file."\n");
1.572     banghart 10619:     }
1.574     banghart 10620:     close (OUT);
1.572     banghart 10621:     return 'ok';
                   10622: }
                   10623: 
1.574     banghart 10624: sub clear_selected_files {
                   10625:     my ($user) = @_;
                   10626:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10627:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10628:     print (OUT undef);
                   10629:     close (OUT);
                   10630:     return ("ok");    
                   10631: }
                   10632: 
1.572     banghart 10633: sub files_in_path {
                   10634:     my ($user, $path) = @_;
                   10635:     my $filename = $user."savedfiles";
                   10636:     my %return_files;
1.1172.2.96  raeburn  10637:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10638:     while (my $line_in = <IN>) {
1.574     banghart 10639:         chomp ($line_in);
                   10640:         my @paths_and_file = split (m!/!, $line_in);
                   10641:         my $file_part = pop (@paths_and_file);
                   10642:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10643:         $path_part.='/';
                   10644:         my $path_and_file = $path_part.$file_part;
                   10645:         if ($path_part eq $path) {
                   10646:             $return_files{$file_part}= 'selected';
                   10647:         }
                   10648:     }
1.574     banghart 10649:     close (IN);
                   10650:     return (\%return_files);
1.572     banghart 10651: }
                   10652: 
                   10653: # called in portfolio select mode, to show files selected NOT in current directory
                   10654: sub files_not_in_path {
                   10655:     my ($user, $path) = @_;
                   10656:     my $filename = $user."savedfiles";
                   10657:     my @return_files;
                   10658:     my $path_part;
1.1172.2.96  raeburn  10659:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10660:     while (my $line = <IN>) {
1.572     banghart 10661:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10662:         my @paths_and_file = split(m|/|, $line);
                   10663:         my $file_part = pop(@paths_and_file);
                   10664:         chomp($file_part);
                   10665:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10666:         $path_part .= '/';
                   10667:         my $path_and_file = $path_part.$file_part;
                   10668:         if ($path_part ne $path) {
1.800     albertel 10669:             push(@return_files, ($path_and_file));
1.572     banghart 10670:         }
                   10671:     }
1.800     albertel 10672:     close(OUT);
1.574     banghart 10673:     return (@return_files);
1.572     banghart 10674: }
                   10675: 
1.745     raeburn  10676: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10677: 
1.745     raeburn  10678: sub get_portfile_permissions {
                   10679:     my ($domain,$user) = @_;
1.613     albertel 10680:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10681:     my ($tmp)=keys(%current_permissions);
                   10682:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10683:     return \%current_permissions;
                   10684: }
                   10685: 
                   10686: #---------------------------------------------Get portfolio file access controls
                   10687: 
1.749     raeburn  10688: sub get_access_controls {
1.745     raeburn  10689:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10690:     my %access;
                   10691:     my $real_file = $file;
                   10692:     $file =~ s/\.meta$//;
1.745     raeburn  10693:     if (defined($file)) {
1.749     raeburn  10694:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10695:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10696:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10697:             }
                   10698:         }
1.745     raeburn  10699:     } else {
1.749     raeburn  10700:         foreach my $key (keys(%{$current_permissions})) {
                   10701:             if ($key =~ /\0accesscontrol$/) {
                   10702:                 if (defined($group)) {
                   10703:                     if ($key !~ m-^\Q$group\E/-) {
                   10704:                         next;
                   10705:                     }
                   10706:                 }
                   10707:                 my ($fullpath) = split(/\0/,$key);
                   10708:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10709:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10710:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10711:                     }
                   10712:                 }
                   10713:             }
                   10714:         }
                   10715:     }
                   10716:     return %access;
                   10717: }
                   10718: 
                   10719: sub modify_access_controls {
                   10720:     my ($file_name,$changes,$domain,$user)=@_;
                   10721:     my ($outcome,$deloutcome);
                   10722:     my %store_permissions;
                   10723:     my %new_values;
                   10724:     my %new_control;
                   10725:     my %translation;
                   10726:     my @deletions = ();
                   10727:     my $now = time;
                   10728:     if (exists($$changes{'activate'})) {
                   10729:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10730:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10731:             my $numnew = scalar(@newitems);
                   10732:             for (my $i=0; $i<$numnew; $i++) {
                   10733:                 my $newkey = $newitems[$i];
                   10734:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10735:                 if ($newkey =~ /^\d+:/) { 
                   10736:                     $newkey =~ s/^(\d+)/$newid/;
                   10737:                     $translation{$1} = $newid;
                   10738:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10739:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10740:                     $translation{$1} = $newid;
                   10741:                 }
1.749     raeburn  10742:                 $new_values{$file_name."\0".$newkey} = 
                   10743:                                           $$changes{'activate'}{$newitems[$i]};
                   10744:                 $new_control{$newkey} = $now;
                   10745:             }
                   10746:         }
                   10747:     }
                   10748:     my %todelete;
                   10749:     my %changed_items;
                   10750:     foreach my $action ('delete','update') {
                   10751:         if (exists($$changes{$action})) {
                   10752:             if (ref($$changes{$action}) eq 'HASH') {
                   10753:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10754:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10755:                     if ($action eq 'delete') { 
                   10756:                         $todelete{$itemnum} = 1;
                   10757:                     } else {
                   10758:                         $changed_items{$itemnum} = $key;
                   10759:                     }
                   10760:                 }
1.745     raeburn  10761:             }
                   10762:         }
1.749     raeburn  10763:     }
                   10764:     # get lock on access controls for file.
                   10765:     my $lockhash = {
                   10766:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10767:                                                        ':'.$env{'user.domain'},
                   10768:                    }; 
                   10769:     my $tries = 0;
                   10770:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10771:    
1.1172.2.79  raeburn  10772:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10773:         $tries ++;
1.1172.2.79  raeburn  10774:         sleep(0.1);
1.749     raeburn  10775:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10776:     }
                   10777:     if ($gotlock eq 'ok') {
                   10778:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10779:         my ($tmp)=keys(%curr_permissions);
                   10780:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10781:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10782:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10783:             if (ref($curr_controls) eq 'HASH') {
                   10784:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10785:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10786:                     if (defined($todelete{$itemnum})) {
                   10787:                         push(@deletions,$file_name."\0".$control_item);
                   10788:                     } else {
                   10789:                         if (defined($changed_items{$itemnum})) {
                   10790:                             $new_control{$changed_items{$itemnum}} = $now;
                   10791:                             push(@deletions,$file_name."\0".$control_item);
                   10792:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10793:                         } else {
                   10794:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10795:                         }
                   10796:                     }
1.745     raeburn  10797:                 }
                   10798:             }
                   10799:         }
1.970     raeburn  10800:         my ($group);
                   10801:         if (&is_course($domain,$user)) {
                   10802:             ($group,my $file) = split(/\//,$file_name,2);
                   10803:         }
1.749     raeburn  10804:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10805:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10806:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10807:         #  remove lock
                   10808:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10809:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10810:         my $sqlresult =
1.970     raeburn  10811:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10812:                                     $group);
1.749     raeburn  10813:     } else {
                   10814:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10815:     }
1.749     raeburn  10816:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10817: }
                   10818: 
1.827     raeburn  10819: sub make_public_indefinitely {
                   10820:     my ($requrl) = @_;
                   10821:     my $now = time;
                   10822:     my $action = 'activate';
                   10823:     my $aclnum = 0;
                   10824:     if (&is_portfolio_url($requrl)) {
                   10825:         my (undef,$udom,$unum,$file_name,$group) =
                   10826:             &parse_portfolio_url($requrl);
                   10827:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10828:         my %access_controls = &get_access_controls($current_perms,
                   10829:                                                    $group,$file_name);
                   10830:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10831:             my ($num,$scope,$end,$start) = 
                   10832:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10833:             if ($scope eq 'public') {
                   10834:                 if ($start <= $now && $end == 0) {
                   10835:                     $action = 'none';
                   10836:                 } else {
                   10837:                     $action = 'update';
                   10838:                     $aclnum = $num;
                   10839:                 }
                   10840:                 last;
                   10841:             }
                   10842:         }
                   10843:         if ($action eq 'none') {
                   10844:              return 'ok';
                   10845:         } else {
                   10846:             my %changes;
                   10847:             my $newend = 0;
                   10848:             my $newstart = $now;
                   10849:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10850:             $changes{$action}{$newkey} = {
                   10851:                 type => 'public',
                   10852:                 time => {
                   10853:                     start => $newstart,
                   10854:                     end   => $newend,
                   10855:                 },
                   10856:             };
                   10857:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10858:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10859:             return $outcome;
                   10860:         }
                   10861:     } else {
                   10862:         return 'invalid';
                   10863:     }
                   10864: }
                   10865: 
1.745     raeburn  10866: #------------------------------------------------------Get Marked as Read Only
                   10867: 
                   10868: sub get_marked_as_readonly {
                   10869:     my ($domain,$user,$what,$group) = @_;
                   10870:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10871:     my @readonly_files;
1.629     banghart 10872:     my $cmp1=$what;
                   10873:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10874:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10875:         if (defined($group)) {
                   10876:             if ($file_name !~ m-^\Q$group\E/-) {
                   10877:                 next;
                   10878:             }
                   10879:         }
1.561     banghart 10880:         if (ref($value) eq "ARRAY"){
                   10881:             foreach my $stored_what (@{$value}) {
1.629     banghart 10882:                 my $cmp2=$stored_what;
1.759     albertel 10883:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10884:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10885:                 }
1.629     banghart 10886:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10887:                     push(@readonly_files, $file_name);
1.745     raeburn  10888:                     last;
1.563     banghart 10889:                 } elsif (!defined($what)) {
                   10890:                     push(@readonly_files, $file_name);
1.745     raeburn  10891:                     last;
1.561     banghart 10892:                 }
                   10893:             }
1.745     raeburn  10894:         }
1.561     banghart 10895:     }
                   10896:     return @readonly_files;
                   10897: }
1.577     banghart 10898: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10899: 
1.577     banghart 10900: sub get_marked_as_readonly_hash {
1.745     raeburn  10901:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10902:     my %readonly_files;
1.745     raeburn  10903:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10904:         if (defined($group)) {
                   10905:             if ($file_name !~ m-^\Q$group\E/-) {
                   10906:                 next;
                   10907:             }
                   10908:         }
1.577     banghart 10909:         if (ref($value) eq "ARRAY"){
                   10910:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10911:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10912:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10913:                         if ($lock_descriptor eq 'graded') {
                   10914:                             $readonly_files{$file_name} = 'graded';
                   10915:                         } elsif ($lock_descriptor eq 'handback') {
                   10916:                             $readonly_files{$file_name} = 'handback';
                   10917:                         } else {
                   10918:                             if (!exists($readonly_files{$file_name})) {
                   10919:                                 $readonly_files{$file_name} = 'locked';
                   10920:                             }
                   10921:                         }
1.745     raeburn  10922:                     }
1.750     banghart 10923:                 } 
1.577     banghart 10924:             }
                   10925:         } 
                   10926:     }
                   10927:     return %readonly_files;
                   10928: }
1.559     banghart 10929: # ------------------------------------------------------------ Unmark as Read Only
                   10930: 
                   10931: sub unmark_as_readonly {
1.629     banghart 10932:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10933:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10934:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10935:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10936:     my $symb_crs = $what;
                   10937:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10938:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10939:     my ($tmp)=keys(%current_permissions);
                   10940:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10941:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10942:     foreach my $file (@readonly_files) {
1.759     albertel 10943: 	my $clean_file = &declutter_portfile($file);
                   10944: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10945: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10946:         my @new_locks;
                   10947:         my @del_keys;
                   10948:         if (ref($current_locks) eq "ARRAY"){
                   10949:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10950:                 my $compare=$locker;
1.749     raeburn  10951:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10952:                     $compare=join('',@{$locker});
1.746     raeburn  10953:                     if ($compare ne $symb_crs) {
                   10954:                         push(@new_locks, $locker);
                   10955:                     }
1.563     banghart 10956:                 }
                   10957:             }
1.650     albertel 10958:             if (scalar(@new_locks) > 0) {
1.563     banghart 10959:                 $current_permissions{$file} = \@new_locks;
                   10960:             } else {
                   10961:                 push(@del_keys, $file);
1.613     albertel 10962:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10963:                 delete($current_permissions{$file});
1.563     banghart 10964:             }
                   10965:         }
1.561     banghart 10966:     }
1.613     albertel 10967:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10968:     return;
                   10969: }
1.512     banghart 10970: 
1.17      www      10971: # ------------------------------------------------------------ Directory lister
                   10972: 
                   10973: sub dirlist {
1.955     raeburn  10974:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10975:     $uri=~s/^\///;
                   10976:     $uri=~s/\/$//;
1.253     stredwic 10977:     my ($udom, $uname);
1.955     raeburn  10978:     if ($getuserdir) {
1.253     stredwic 10979:         $udom = $userdomain;
                   10980:         $uname = $username;
1.955     raeburn  10981:     } else {
                   10982:         (undef,$udom,$uname)=split(/\//,$uri);
                   10983:         if(defined($userdomain)) {
                   10984:             $udom = $userdomain;
                   10985:         }
                   10986:         if(defined($username)) {
                   10987:             $uname = $username;
                   10988:         }
1.253     stredwic 10989:     }
1.955     raeburn  10990:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10991: 
1.955     raeburn  10992:     $dirRoot = $perlvar{'lonDocRoot'};
                   10993:     if (defined($getpropath)) {
                   10994:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10995:         $dirRoot =~ s/\/$//;
1.955     raeburn  10996:     } elsif (defined($getuserdir)) {
                   10997:         my $subdir=$uname.'__';
                   10998:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10999:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11000:                    ."/$udom/$subdir/$uname";
                   11001:     } elsif (defined($alternateRoot)) {
                   11002:         $dirRoot = $alternateRoot;
1.751     banghart 11003:     }
1.253     stredwic 11004: 
                   11005:     if($udom) {
                   11006:         if($uname) {
1.1135    raeburn  11007:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11008:             if ($uhome eq 'no_host') {
                   11009:                 return ([],'no_host');
                   11010:             }
1.955     raeburn  11011:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11012:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11013:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11014:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11015:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11016:             } else {
                   11017:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11018:             }
1.605     matthew  11019:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11020:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11021:                 @listing_results = split(/:/,$listing);
                   11022:             } else {
                   11023:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11024:             }
1.1135    raeburn  11025:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11026:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11027:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11028:                 return ([],$listing);
                   11029:             } else {
                   11030:                 return (\@listing_results);
1.1135    raeburn  11031:             }
1.955     raeburn  11032:         } elsif(!$alternateRoot) {
1.1136    raeburn  11033:             my (%allusers,%listerror);
1.841     albertel 11034: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11035:  	    foreach my $tryserver (keys(%servers)) {
                   11036:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11037:                                   &escape($udom),$tryserver);
                   11038:                 if ($listing eq 'unknown_cmd') {
                   11039: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11040: 				      $udom, $tryserver);
                   11041:                 } else {
                   11042:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11043:                 }
1.841     albertel 11044: 		if ($listing eq 'unknown_cmd') {
                   11045: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11046: 				      $udom, $tryserver);
                   11047: 		    @listing_results = split(/:/,$listing);
                   11048: 		} else {
                   11049: 		    @listing_results =
                   11050: 			map { &unescape($_); } split(/:/,$listing);
                   11051: 		}
1.1136    raeburn  11052:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11053:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11054:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11055:                     $listerror{$tryserver} = $listing;
                   11056:                 } else {
1.841     albertel 11057: 		    foreach my $line (@listing_results) {
                   11058: 			my ($entry) = split(/&/,$line,2);
                   11059: 			$allusers{$entry} = 1;
                   11060: 		    }
                   11061: 		}
1.253     stredwic 11062:             }
1.1136    raeburn  11063:             my @alluserslist=();
1.800     albertel 11064:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11065:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11066:             }
1.1172.2.80  raeburn  11067:             if (!%listerror) {
                   11068:                 # no errors
                   11069:                 return (\@alluserslist);
                   11070:             } elsif (scalar(keys(%servers)) == 1) {
                   11071:                 # one library server, one error
                   11072:                 my ($key) = keys(%listerror);
                   11073:                 return (\@alluserslist, $listerror{$key});
                   11074:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11075:                 # con_lost indicates that we might miss data from at least one
                   11076:                 # library server
                   11077:                 return (\@alluserslist, 'con_lost');
                   11078:             } else {
                   11079:                 # multiple library servers and no con_lost -> data should be
                   11080:                 # complete.
                   11081:                 return (\@alluserslist);
                   11082:             }
                   11083: 
1.253     stredwic 11084:         } else {
1.1136    raeburn  11085:             return ([],'missing username');
1.253     stredwic 11086:         }
1.955     raeburn  11087:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11088:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11089:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11090:         return (\@all_domains);
1.955     raeburn  11091:     } else {
1.1136    raeburn  11092:         return ([],'missing domain');
1.275     stredwic 11093:     }
                   11094: }
                   11095: 
                   11096: # --------------------------------------------- GetFileTimestamp
                   11097: # This function utilizes dirlist and returns the date stamp for
                   11098: # when it was last modified.  It will also return an error of -1
                   11099: # if an error occurs
                   11100: 
                   11101: sub GetFileTimestamp {
1.955     raeburn  11102:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11103:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11104:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11105:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11106:                                     undef,$getuserdir);
                   11107:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11108:         return -1;
                   11109:     }
                   11110:     if (ref($fileref) eq 'ARRAY') {
                   11111:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11112:         # @stats contains first the filename, then the stat output
                   11113:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11114:     } else {
                   11115:         return -1;
1.253     stredwic 11116:     }
1.26      www      11117: }
                   11118: 
1.712     albertel 11119: sub stat_file {
                   11120:     my ($uri) = @_;
1.787     albertel 11121:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11122: 
1.955     raeburn  11123:     my ($udom,$uname,$file);
1.712     albertel 11124:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11125: 	($udom,$uname,$file) =
1.811     albertel 11126: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11127: 	$file = 'userfiles/'.$file;
                   11128:     }
                   11129:     if ($uri =~ m-^/res/-) {
                   11130: 	($udom,$uname) = 
1.807     albertel 11131: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11132: 	$file = $uri;
                   11133:     }
                   11134: 
                   11135:     if (!$udom || !$uname || !$file) {
                   11136: 	# unable to handle the uri
                   11137: 	return ();
                   11138:     }
1.956     raeburn  11139:     my $getpropath;
                   11140:     if ($file =~ /^userfiles\//) {
                   11141:         $getpropath = 1;
                   11142:     }
1.1136    raeburn  11143:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11144:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11145:         return ();
                   11146:     } else {
                   11147:         if (ref($listref) eq 'ARRAY') {
                   11148:             my @stats = split('&',$listref->[0]);
                   11149: 	    shift(@stats); #filename is first
                   11150: 	    return @stats;
                   11151:         }
1.712     albertel 11152:     }
                   11153:     return ();
                   11154: }
                   11155: 
1.26      www      11156: # -------------------------------------------------------- Value of a Condition
                   11157: 
1.713     albertel 11158: # gets the value of a specific preevaluated condition
                   11159: #    stored in the string  $env{user.state.<cid>}
                   11160: # or looks up a condition reference in the bighash and if if hasn't
                   11161: # already been evaluated recurses into docondval to get the value of
                   11162: # the condition, then memoizing it to 
                   11163: #   $env{user.state.<cid>.<condition>}
1.40      www      11164: sub directcondval {
                   11165:     my $number=shift;
1.620     albertel 11166:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11167: 	&Apache::lonuserstate::evalstate();
                   11168:     }
1.713     albertel 11169:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11170: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11171:     } elsif ($number =~ /^_/) {
                   11172: 	my $sub_condition;
                   11173: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11174: 		&GDBM_READER(),0640)) {
                   11175: 	    $sub_condition=$bighash{'conditions'.$number};
                   11176: 	    untie(%bighash);
                   11177: 	}
                   11178: 	my $value = &docondval($sub_condition);
1.949     raeburn  11179: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11180: 	return $value;
                   11181:     }
1.620     albertel 11182:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11183:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11184:     } else {
                   11185:        return 2;
                   11186:     }
                   11187: }
                   11188: 
1.713     albertel 11189: # get the collection of conditions for this resource
1.26      www      11190: sub condval {
                   11191:     my $condidx=shift;
1.54      www      11192:     my $allpathcond='';
1.713     albertel 11193:     foreach my $cond (split(/\|/,$condidx)) {
                   11194: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11195: 	    $allpathcond.=
                   11196: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11197: 	}
1.191     harris41 11198:     }
1.54      www      11199:     $allpathcond=~s/\|$//;
1.713     albertel 11200:     return &docondval($allpathcond);
                   11201: }
                   11202: 
                   11203: #evaluates an expression of conditions
                   11204: sub docondval {
                   11205:     my ($allpathcond) = @_;
                   11206:     my $result=0;
                   11207:     if ($env{'request.course.id'}
                   11208: 	&& defined($allpathcond)) {
                   11209: 	my $operand='|';
                   11210: 	my @stack;
                   11211: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11212: 	    if ($chunk eq '(') {
                   11213: 		push @stack,($operand,$result);
                   11214: 	    } elsif ($chunk eq ')') {
                   11215: 		my $before=pop @stack;
                   11216: 		if (pop @stack eq '&') {
                   11217: 		    $result=$result>$before?$before:$result;
                   11218: 		} else {
                   11219: 		    $result=$result>$before?$result:$before;
                   11220: 		}
                   11221: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11222: 		$operand=$chunk;
                   11223: 	    } else {
                   11224: 		my $new=directcondval($chunk);
                   11225: 		if ($operand eq '&') {
                   11226: 		    $result=$result>$new?$new:$result;
                   11227: 		} else {
                   11228: 		    $result=$result>$new?$result:$new;
                   11229: 		}
                   11230: 	    }
                   11231: 	}
1.26      www      11232:     }
                   11233:     return $result;
1.421     albertel 11234: }
                   11235: 
                   11236: # ---------------------------------------------------- Devalidate courseresdata
                   11237: 
                   11238: sub devalidatecourseresdata {
                   11239:     my ($coursenum,$coursedomain)=@_;
                   11240:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11241:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11242: }
                   11243: 
1.763     www      11244: 
1.200     www      11245: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11246: #
                   11247: #  Parameters:
                   11248: #      $coursenum    - Number of the course.
                   11249: #      $coursedomain - Domain at which the course was created.
                   11250: #  Returns:
                   11251: #     A hash of the course parameters along (I think) with timestamps
                   11252: #     and version info.
1.877     foxr     11253: 
1.624     albertel 11254: sub get_courseresdata {
                   11255:     my ($coursenum,$coursedomain)=@_;
1.200     www      11256:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11257:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11258:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11259:     my %dumpreply;
1.417     albertel 11260:     unless (defined($cached)) {
1.624     albertel 11261: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11262: 	$result=\%dumpreply;
1.251     albertel 11263: 	my ($tmp) = keys(%dumpreply);
                   11264: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11265: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11266: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11267: 	    return $tmp;
1.416     albertel 11268: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11269: 	    $result=undef;
1.599     albertel 11270: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11271: 	}
                   11272:     }
1.624     albertel 11273:     return $result;
                   11274: }
                   11275: 
1.633     albertel 11276: sub devalidateuserresdata {
                   11277:     my ($uname,$udom)=@_;
                   11278:     my $hashid="$udom:$uname";
                   11279:     &devalidate_cache_new('userres',$hashid);
                   11280: }
                   11281: 
1.624     albertel 11282: sub get_userresdata {
                   11283:     my ($uname,$udom)=@_;
                   11284:     #most student don\'t have any data set, check if there is some data
                   11285:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11286: 
                   11287:     my $hashid="$udom:$uname";
                   11288:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11289:     if (!defined($cached)) {
                   11290: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11291: 	$result=\%resourcedata;
                   11292: 	&do_cache_new('userres',$hashid,$result,600);
                   11293:     }
                   11294:     my ($tmp)=keys(%$result);
                   11295:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11296: 	return $result;
                   11297:     }
                   11298:     #error 2 occurs when the .db doesn't exist
                   11299:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11300:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11301: 	    &logthis("<font color=\"blue\">WARNING:".
                   11302: 		     " Trying to get resource data for ".
                   11303: 		     $uname." at ".$udom.": ".
                   11304: 		     $tmp."</font>");
                   11305:         }
1.624     albertel 11306:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11307: 	#&EXT_cache_set($udom,$uname);
                   11308: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11309: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11310:     }
                   11311:     return $tmp;
                   11312: }
1.879     foxr     11313: #----------------------------------------------- resdata - return resource data
                   11314: #  Purpose:
                   11315: #    Return resource data for either users or for a course.
                   11316: #  Parameters:
                   11317: #     $name      - Course/user name.
                   11318: #     $domain    - Name of the domain the user/course is registered on.
                   11319: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11320: #     @which     - Array of names of resources desired.
                   11321: #  Returns:
                   11322: #     The value of the first reasource in @which that is found in the
                   11323: #     resource hash.
                   11324: #  Exceptional Conditions:
                   11325: #     If the $type passed in is not valid (not the string 'course' or 
                   11326: #     'user', an undefined  reference is returned.
                   11327: #     If none of the resources are found, an undef is returned
1.624     albertel 11328: sub resdata {
                   11329:     my ($name,$domain,$type,@which)=@_;
                   11330:     my $result;
                   11331:     if ($type eq 'course') {
                   11332: 	$result=&get_courseresdata($name,$domain);
                   11333:     } elsif ($type eq 'user') {
                   11334: 	$result=&get_userresdata($name,$domain);
                   11335:     }
                   11336:     if (!ref($result)) { return $result; }    
1.251     albertel 11337:     foreach my $item (@which) {
1.927     albertel 11338: 	if (defined($result->{$item->[0]})) {
                   11339: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11340: 	}
1.250     albertel 11341:     }
1.291     albertel 11342:     return undef;
1.200     www      11343: }
                   11344: 
1.1172.2.31  raeburn  11345: sub get_numsuppfiles {
                   11346:     my ($cnum,$cdom,$ignorecache)=@_;
                   11347:     my $hashid=$cnum.':'.$cdom;
                   11348:     my ($suppcount,$cached);
                   11349:     unless ($ignorecache) {
                   11350:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11351:     }
                   11352:     unless (defined($cached)) {
                   11353:         my $chome=&homeserver($cnum,$cdom);
                   11354:         unless ($chome eq 'no_host') {
                   11355:             ($suppcount,my $errors) = (0,0);
                   11356:             my $suppmap = 'supplemental.sequence';
                   11357:             ($suppcount,$errors) =
                   11358:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11359:         }
                   11360:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11361:     }
                   11362:     return $suppcount;
                   11363: }
                   11364: 
1.379     matthew  11365: #
                   11366: # EXT resource caching routines
                   11367: #
                   11368: 
                   11369: sub clear_EXT_cache_status {
1.383     albertel 11370:     &delenv('cache.EXT.');
1.379     matthew  11371: }
                   11372: 
                   11373: sub EXT_cache_status {
                   11374:     my ($target_domain,$target_user) = @_;
1.383     albertel 11375:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11376:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11377:         # We know already the user has no data
                   11378:         return 1;
                   11379:     } else {
                   11380:         return 0;
                   11381:     }
                   11382: }
                   11383: 
                   11384: sub EXT_cache_set {
                   11385:     my ($target_domain,$target_user) = @_;
1.383     albertel 11386:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11387:     #&appenv({$cachename => time});
1.379     matthew  11388: }
                   11389: 
1.28      www      11390: # --------------------------------------------------------- Value of a Variable
1.58      www      11391: sub EXT {
1.715     albertel 11392: 
1.1172.2.28  raeburn  11393:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11394:     unless ($varname) { return ''; }
1.218     albertel 11395:     #get real user name/domain, courseid and symb
                   11396:     my $courseid;
1.359     albertel 11397:     my $publicuser;
1.427     www      11398:     if ($symbparm) {
                   11399: 	$symbparm=&get_symb_from_alias($symbparm);
                   11400:     }
1.218     albertel 11401:     if (!($uname && $udom)) {
1.790     albertel 11402:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11403:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11404:     } else {
1.620     albertel 11405: 	$courseid=$env{'request.course.id'};
1.218     albertel 11406:     }
1.48      www      11407:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11408:     my $rest;
1.320     albertel 11409:     if (defined($therest[0])) {
1.48      www      11410:        $rest=join('.',@therest);
                   11411:     } else {
                   11412:        $rest='';
                   11413:     }
1.320     albertel 11414: 
1.57      www      11415:     my $qualifierrest=$qualifier;
                   11416:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11417:     my $spacequalifierrest=$space;
                   11418:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11419:     if ($realm eq 'user') {
1.48      www      11420: # --------------------------------------------------------------- user.resource
                   11421: 	if ($space eq 'resource') {
1.651     albertel 11422: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11423: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11424: 		 &&
1.744     albertel 11425: 		 ($symbparm eq &symbread()) ) {	
                   11426: 		# if we are in the middle of processing the resource the
                   11427: 		# get the value we are planning on committing
                   11428:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11429:                     return $Apache::lonhomework::results{$qualifierrest};
                   11430:                 } else {
                   11431:                     return $Apache::lonhomework::history{$qualifierrest};
                   11432:                 }
1.335     albertel 11433: 	    } else {
1.359     albertel 11434: 		my %restored;
1.620     albertel 11435: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11436: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11437: 		} else {
                   11438: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11439: 		}
1.335     albertel 11440: 		return $restored{$qualifierrest};
                   11441: 	    }
1.48      www      11442: # ----------------------------------------------------------------- user.access
                   11443:         } elsif ($space eq 'access') {
1.218     albertel 11444: 	    # FIXME - not supporting calls for a specific user
1.48      www      11445:             return &allowed($qualifier,$rest);
                   11446: # ------------------------------------------ user.preferences, user.environment
                   11447:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11448: 	    if (($uname eq $env{'user.name'}) &&
                   11449: 		($udom eq $env{'user.domain'})) {
                   11450: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11451: 	    } else {
1.359     albertel 11452: 		my %returnhash;
                   11453: 		if (!$publicuser) {
                   11454: 		    %returnhash=&userenvironment($udom,$uname,
                   11455: 						 $qualifierrest);
                   11456: 		}
1.218     albertel 11457: 		return $returnhash{$qualifierrest};
                   11458: 	    }
1.48      www      11459: # ----------------------------------------------------------------- user.course
                   11460:         } elsif ($space eq 'course') {
1.218     albertel 11461: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11462:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11463: # ------------------------------------------------------------------- user.role
                   11464:         } elsif ($space eq 'role') {
1.218     albertel 11465: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11466:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11467:             if ($qualifier eq 'value') {
                   11468: 		return $role;
                   11469:             } elsif ($qualifier eq 'extent') {
                   11470:                 return $where;
                   11471:             }
                   11472: # ----------------------------------------------------------------- user.domain
                   11473:         } elsif ($space eq 'domain') {
1.218     albertel 11474:             return $udom;
1.48      www      11475: # ------------------------------------------------------------------- user.name
                   11476:         } elsif ($space eq 'name') {
1.218     albertel 11477:             return $uname;
1.48      www      11478: # ---------------------------------------------------- Any other user namespace
1.29      www      11479:         } else {
1.359     albertel 11480: 	    my %reply;
                   11481: 	    if (!$publicuser) {
                   11482: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11483: 	    }
                   11484: 	    return $reply{$qualifierrest};
1.48      www      11485:         }
1.236     www      11486:     } elsif ($realm eq 'query') {
                   11487: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11488:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11489: 						[$spacequalifierrest]);
1.620     albertel 11490: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11491:    } elsif ($realm eq 'request') {
1.48      www      11492: # ------------------------------------------------------------- request.browser
                   11493:         if ($space eq 'browser') {
1.1145    bisitz   11494:             return $env{'browser.'.$qualifier};
1.57      www      11495: # ------------------------------------------------------------ request.filename
                   11496:         } else {
1.620     albertel 11497:             return $env{'request.'.$spacequalifierrest};
1.29      www      11498:         }
1.28      www      11499:     } elsif ($realm eq 'course') {
1.48      www      11500: # ---------------------------------------------------------- course.description
1.620     albertel 11501:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11502:     } elsif ($realm eq 'resource') {
1.165     www      11503: 
1.620     albertel 11504: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11505: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11506: 	}
1.693     albertel 11507: 
1.1172.2.30  raeburn  11508:         if ($qualifier eq '') {
                   11509: 	    if ($space eq 'title') {
                   11510: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11511: 	        return &gettitle($symbparm);
                   11512: 	    }
1.693     albertel 11513: 	
1.1172.2.30  raeburn  11514: 	    if ($space eq 'map') {
                   11515: 	        my ($map) = &decode_symb($symbparm);
                   11516: 	        return &symbread($map);
                   11517: 	    }
                   11518:             if ($space eq 'maptitle') {
                   11519:                 my ($map) = &decode_symb($symbparm);
                   11520:                 return &gettitle($map);
                   11521:             }
                   11522: 	    if ($space eq 'filename') {
                   11523: 	        if ($symbparm) {
                   11524: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11525: 	        }
                   11526: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11527: 	    }
1.1172.2.30  raeburn  11528: 
                   11529:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11530:                 if ($space eq 'visibleparts') {
                   11531:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11532:                     my $item;
                   11533:                     if (ref($navmap)) {
                   11534:                         my $res = $navmap->getBySymb($symbparm);
                   11535:                         my $parts = $res->parts();
                   11536:                         if (ref($parts) eq 'ARRAY') {
                   11537:                             $item = join(',',@{$parts});
                   11538:                         }
                   11539:                         undef($navmap);
                   11540:                     }
                   11541:                     return $item;
                   11542:                 }
                   11543:             }
                   11544:         }
1.693     albertel 11545: 
                   11546: 	my ($section, $group, @groups);
1.593     albertel 11547: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11548:         if (($courseid eq '') && ($cid)) {
                   11549:             $courseid = $cid;
                   11550:         }
                   11551: 	if (($symbparm && $courseid) && 
                   11552: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11553: 
1.218     albertel 11554: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11555: 
1.60      www      11556: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11557: 	    my $symbp=$symbparm;
1.735     albertel 11558: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11559: 
                   11560: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11561: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11562: 
1.620     albertel 11563: 	    if (($env{'user.name'} eq $uname) &&
                   11564: 		($env{'user.domain'} eq $udom)) {
                   11565: 		$section=$env{'request.course.sec'};
1.733     raeburn  11566:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11567:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11568: 	    } else {
1.539     albertel 11569: 		if (! defined($usection)) {
1.551     albertel 11570: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11571: 		} else {
                   11572: 		    $section = $usection;
                   11573: 		}
1.733     raeburn  11574:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11575: 	    }
                   11576: 
                   11577: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11578: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11579: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11580: 
1.593     albertel 11581: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11582: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11583: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11584: 
1.60      www      11585: # ----------------------------------------------------------- first, check user
1.624     albertel 11586: 
                   11587: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11588: 				       ([$courselevelr,'resource'],
                   11589: 					[$courselevelm,'map'     ],
                   11590: 					[$courselevel, 'course'  ]));
1.931     albertel 11591: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11592: 
1.594     albertel 11593: # ------------------------------------------------ second, check some of course
1.684     raeburn  11594:             my $coursereply;
1.691     raeburn  11595:             if (@groups > 0) {
                   11596:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11597:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11598:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11599:             }
1.96      www      11600: 
1.684     raeburn  11601: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11602: 				  $env{'course.'.$courseid.'.domain'},
                   11603: 				  'course',
                   11604: 				  ([$seclevelr,   'resource'],
                   11605: 				   [$seclevelm,   'map'     ],
                   11606: 				   [$seclevel,    'course'  ],
                   11607: 				   [$courselevelr,'resource']));
                   11608: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11609: 
1.60      www      11610: # ------------------------------------------------------ third, check map parms
1.218     albertel 11611: 	    my %parmhash=();
                   11612: 	    my $thisparm='';
                   11613: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11614: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11615: 		    &GDBM_READER(),0640)) {
1.218     albertel 11616: 		$thisparm=$parmhash{$symbparm};
                   11617: 		untie(%parmhash);
                   11618: 	    }
1.927     albertel 11619: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11620: 	}
1.594     albertel 11621: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11622: 
1.218     albertel 11623: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11624: 	my $filename;
                   11625: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11626: 	if ($symbparm) {
1.409     www      11627: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11628: 	} else {
1.620     albertel 11629: 	    $filename=$env{'request.filename'};
1.282     albertel 11630: 	}
                   11631: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11632: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11633: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11634: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11635: 
1.927     albertel 11636: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11637: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11638: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11639: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11640: 				     $env{'course.'.$courseid.'.domain'},
                   11641: 				     'course',
1.927     albertel 11642: 				     ([$courselevelm,'map'   ],
                   11643: 				      [$courselevel, 'course']));
                   11644: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11645: 	}
1.145     www      11646: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11647: 	unless ($space eq '0') {
1.336     albertel 11648: 	    my @parts=split(/_/,$space);
                   11649: 	    my $id=pop(@parts);
                   11650: 	    my $part=join('_',@parts);
                   11651: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11652: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11653: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11654: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11655: 	}
1.395     albertel 11656: 	if ($recurse) { return undef; }
                   11657: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11658: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11659: # ---------------------------------------------------- Any other user namespace
                   11660:     } elsif ($realm eq 'environment') {
                   11661: # ----------------------------------------------------------------- environment
1.620     albertel 11662: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11663: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11664: 	} else {
1.770     albertel 11665: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11666: 		return '';
                   11667: 	    }
1.219     albertel 11668: 	    my %returnhash=&userenvironment($udom,$uname,
                   11669: 					    $spacequalifierrest);
                   11670: 	    return $returnhash{$spacequalifierrest};
                   11671: 	}
1.28      www      11672:     } elsif ($realm eq 'system') {
1.48      www      11673: # ----------------------------------------------------------------- system.time
                   11674: 	if ($space eq 'time') {
                   11675: 	    return time;
                   11676:         }
1.696     albertel 11677:     } elsif ($realm eq 'server') {
                   11678: # ----------------------------------------------------------------- system.time
                   11679: 	if ($space eq 'name') {
                   11680: 	    return $ENV{'SERVER_NAME'};
                   11681:         }
1.28      www      11682:     }
1.48      www      11683:     return '';
1.61      www      11684: }
                   11685: 
1.927     albertel 11686: sub get_reply {
                   11687:     my ($reply_value) = @_;
1.940     raeburn  11688:     if (ref($reply_value) eq 'ARRAY') {
                   11689:         if (wantarray) {
                   11690: 	    return @$reply_value;
                   11691:         }
                   11692:         return $reply_value->[0];
                   11693:     } else {
                   11694:         return $reply_value;
1.927     albertel 11695:     }
                   11696: }
                   11697: 
1.691     raeburn  11698: sub check_group_parms {
                   11699:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11700:     my @groupitems = ();
                   11701:     my $resultitem;
1.927     albertel 11702:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11703:     foreach my $group (@{$groups}) {
                   11704:         foreach my $level (@levels) {
1.927     albertel 11705:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11706:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11707:         }
                   11708:     }
                   11709:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11710:                             $env{'course.'.$courseid.'.domain'},
                   11711:                                      'course',@groupitems);
                   11712:     return $coursereply;
                   11713: }
                   11714: 
                   11715: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11716:     my ($courseid,@groups) = @_;
                   11717:     @groups = sort(@groups);
1.691     raeburn  11718:     return @groups;
                   11719: }
                   11720: 
1.395     albertel 11721: sub packages_tab_default {
                   11722:     my ($uri,$varname)=@_;
                   11723:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11724: 
                   11725:     my (@extension,@specifics,$do_default);
                   11726:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11727: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11728: 	if ($pack_type eq 'default') {
                   11729: 	    $do_default=1;
                   11730: 	} elsif ($pack_type eq 'extension') {
                   11731: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11732: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11733: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11734: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11735: 	}
                   11736:     }
                   11737:     # first look for a package that matches the requested part id
                   11738:     foreach my $package (@specifics) {
                   11739: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11740: 	next if ($pack_part ne $part);
                   11741: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11742: 	    return $packagetab{"$pack_type&$name&default"};
                   11743: 	}
                   11744:     }
                   11745:     # look for any possible matching non extension_ package
                   11746:     foreach my $package (@specifics) {
                   11747: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11748: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11749: 	    return $packagetab{"$pack_type&$name&default"};
                   11750: 	}
1.585     albertel 11751: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11752: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11753: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11754: 	}
                   11755:     }
1.738     albertel 11756:     # look for any posible extension_ match
                   11757:     foreach my $package (@extension) {
                   11758: 	my ($package,$pack_type)=@{$package};
                   11759: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11760: 	    return $packagetab{"$pack_type&$name&default"};
                   11761: 	}
                   11762: 	if (defined($packagetab{$package."&$name&default"})) {
                   11763: 	    return $packagetab{$package."&$name&default"};
                   11764: 	}
                   11765:     }
                   11766:     # look for a global default setting
                   11767:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11768: 	return $packagetab{"default&$name&default"};
                   11769:     }
1.395     albertel 11770:     return undef;
                   11771: }
                   11772: 
1.334     albertel 11773: sub add_prefix_and_part {
                   11774:     my ($prefix,$part)=@_;
                   11775:     my $keyroot;
                   11776:     if (defined($prefix) && $prefix !~ /^__/) {
                   11777: 	# prefix that has a part already
                   11778: 	$keyroot=$prefix;
                   11779:     } elsif (defined($prefix)) {
                   11780: 	# prefix that is missing a part
                   11781: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11782:     } else {
                   11783: 	# no prefix at all
                   11784: 	if (defined($part)) { $keyroot='_'.$part; }
                   11785:     }
                   11786:     return $keyroot;
                   11787: }
                   11788: 
1.71      www      11789: # ---------------------------------------------------------------- Get metadata
                   11790: 
1.599     albertel 11791: my %metaentry;
1.1070    www      11792: my %importedpartids;
1.1172.2.99  raeburn  11793: my %importedrespids;
1.71      www      11794: sub metadata {
1.176     www      11795:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11796:     $uri=&declutter($uri);
1.288     albertel 11797:     # if it is a non metadata possible uri return quickly
1.529     albertel 11798:     if (($uri eq '') || 
                   11799: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11800: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11801:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11802: 	return undef;
                   11803:     }
1.1172.2.49  raeburn  11804:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11805: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11806: 	return undef;
1.288     albertel 11807:     }
1.73      www      11808:     my $filename=$uri;
                   11809:     $uri=~s/\.meta$//;
1.172     www      11810: #
                   11811: # Is the metadata already cached?
1.177     www      11812: # Look at timestamp of caching
1.172     www      11813: # Everything is cached by the main uri, libraries are never directly cached
                   11814: #
1.428     albertel 11815:     if (!defined($liburi)) {
1.599     albertel 11816: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11817: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11818:     }
                   11819:     {
1.1069    www      11820: # Imported parts would go here
1.1172.2.99  raeburn  11821:         my @origfiletagids=();
1.1069    www      11822:         my $importedparts=0;
1.1172.2.99  raeburn  11823: 
                   11824: # Imported responseids would go here
                   11825:         my $importedresponses=0;
1.172     www      11826: #
                   11827: # Is this a recursive call for a library?
                   11828: #
1.599     albertel 11829: #	if (! exists($metacache{$uri})) {
                   11830: #	    $metacache{$uri}={};
                   11831: #	}
1.924     albertel 11832: 	my $cachetime = 60*60;
1.171     www      11833:         if ($liburi) {
                   11834: 	    $liburi=&declutter($liburi);
                   11835:             $filename=$liburi;
1.401     bowersj2 11836:         } else {
1.599     albertel 11837: 	    &devalidate_cache_new('meta',$uri);
                   11838: 	    undef(%metaentry);
1.401     bowersj2 11839: 	}
1.140     www      11840:         my %metathesekeys=();
1.73      www      11841:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11842: 	my $metastring;
1.1140    www      11843: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11844: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11845: 	    $metastring = 
1.929     albertel 11846: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11847: 					  ('grade_target' => 'meta'));
                   11848: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11849: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11850:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11851: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11852: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11853: 	    $metastring=&getfile($file);
1.489     albertel 11854: 	}
1.208     albertel 11855:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11856:         my $token;
1.140     www      11857:         undef %metathesekeys;
1.71      www      11858:         while ($token=$parser->get_token) {
1.339     albertel 11859: 	    if ($token->[0] eq 'S') {
                   11860: 		if (defined($token->[2]->{'package'})) {
1.172     www      11861: #
                   11862: # This is a package - get package info
                   11863: #
1.339     albertel 11864: 		    my $package=$token->[2]->{'package'};
                   11865: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11866: 		    if (defined($token->[2]->{'id'})) { 
                   11867: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11868: 		    }
1.599     albertel 11869: 		    if ($metaentry{':packages'}) {
                   11870: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11871: 		    } else {
1.599     albertel 11872: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11873: 		    }
1.736     albertel 11874: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11875: 			my $part=$keyroot;
                   11876: 			$part=~s/^\_//;
1.736     albertel 11877: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11878: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11879: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11880: 			    # ignore package.tab specified default values
                   11881:                             # here &package_tab_default() will fetch those
                   11882: 			    if ($subp eq 'default') { next; }
1.736     albertel 11883: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11884: 			    my $unikey;
                   11885: 			    if ($pack =~ /_0$/) {
                   11886: 				$unikey='parameter_0_'.$name;
                   11887: 				$part=0;
                   11888: 			    } else {
                   11889: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11890: 			    }
1.339     albertel 11891: 			    if ($subp eq 'display') {
                   11892: 				$value.=' [Part: '.$part.']';
                   11893: 			    }
1.599     albertel 11894: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11895: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11896: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11897: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11898: 			    }
1.599     albertel 11899: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11900: 				$metaentry{':'.$unikey}=
                   11901: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11902: 			    }
1.339     albertel 11903: 			}
                   11904: 		    }
                   11905: 		} else {
1.172     www      11906: #
                   11907: # This is not a package - some other kind of start tag
1.339     albertel 11908: #
                   11909: 		    my $entry=$token->[1];
1.1068    www      11910: 		    my $unikey='';
1.175     www      11911: 
1.339     albertel 11912: 		    if ($entry eq 'import') {
1.175     www      11913: #
                   11914: # Importing a library here
1.339     albertel 11915: #
1.1067    www      11916:                         my $location=$parser->get_text('/import');
                   11917:                         my $dir=$filename;
                   11918:                         $dir=~s|[^/]*$||;
                   11919:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11920: 
                   11921:                         my $importid=$token->[2]->{'id'};
1.1068    www      11922:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11923: #
                   11924: # Check metadata for imported file to
                   11925: # see if it contained response items
                   11926: #
                   11927:                         my %currmetaentry = %metaentry;
                   11928:                         my $libresponseorder = &metadata($location,'responseorder');
                   11929:                         my $origfile;
                   11930:                         if ($libresponseorder ne '') {
                   11931:                             if ($#origfiletagids<0) {
                   11932:                                 undef(%importedrespids);
                   11933:                                 undef(%importedpartids);
                   11934:                             }
                   11935:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11936:                             if (@{$importedrespids{$importid}} > 0) {
                   11937:                                 $importedresponses = 1;
                   11938: # We need to get the original file and the imported file to get the response order correct
                   11939: # Load and inspect original file
                   11940:                                 if ($#origfiletagids<0) {
                   11941:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11942:                                     $origfile=&getfile($origfilelocation);
                   11943:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11944:                                 }
                   11945:                             }
                   11946:                         }
                   11947: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11948: # hash populated for imported library file
                   11949:                         %metaentry = %currmetaentry;
                   11950:                         undef(%currmetaentry);
1.1068    www      11951:                         if ($importmode eq 'problem') {
1.1069    www      11952: # Import as problem/response
1.1068    www      11953:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11954:                         } elsif ($importmode eq 'part') {
                   11955: # Import as part(s)
1.1069    www      11956:                            $importedparts=1;
                   11957: # We need to get the original file and the imported file to get the part order correct
                   11958: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11959: # Load and inspect original file if we didn't do that already
                   11960:                            if ($#origfiletagids<0) {
                   11961:                                undef(%importedrespids);
                   11962:                                undef(%importedpartids);
                   11963:                                if ($origfile eq '') {
                   11964:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11965:                                    $origfile=&getfile($origfilelocation);
                   11966:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11967:                                }
1.1070    www      11968:                            }
                   11969: 
1.1069    www      11970: # Load and inspect imported file
                   11971:                            my $impfile=&getfile($location);
                   11972:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11973:                            if ($#impfilepartids>=0) {
                   11974: # This problem had parts
1.1070    www      11975:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11976:                            } else {
                   11977: # Importing by turning a single problem into a problem part
                   11978: # It gets the import-tags ID as part-ID
                   11979:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11980:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11981:                            }
1.1068    www      11982:                         } else {
                   11983: # Normal import
                   11984:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11985:                            if (defined($token->[2]->{'id'})) {
                   11986:                               $unikey.='_'.$token->[2]->{'id'};
                   11987:                            }
1.1067    www      11988:                         }
                   11989: 
1.339     albertel 11990: 			if ($depthcount<20) {
1.736     albertel 11991: 			    my $metadata = 
                   11992: 				&metadata($uri,'keys', $location,$unikey,
                   11993: 					  $depthcount+1);
                   11994: 			    foreach my $meta (split(',',$metadata)) {
                   11995: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11996: 				$metathesekeys{$meta}=1;
1.339     albertel 11997: 			    }
1.1068    www      11998: 			
                   11999:                         }
1.1067    www      12000: 		    } else {
                   12001: #
                   12002: # Not importing, some other kind of non-package, non-library start tag
                   12003: # 
                   12004:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12005:                         if (defined($token->[2]->{'id'})) {
                   12006:                             $unikey.='_'.$token->[2]->{'id'};
                   12007:                         }
1.339     albertel 12008: 			if (defined($token->[2]->{'name'})) { 
                   12009: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12010: 			}
                   12011: 			$metathesekeys{$unikey}=1;
1.736     albertel 12012: 			foreach my $param (@{$token->[3]}) {
                   12013: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12014: 				$token->[2]->{$param};
1.339     albertel 12015: 			}
                   12016: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12017: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12018: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12019: 		 # only ws inside the tag, and not in default, so use default
                   12020: 		 # as value
1.599     albertel 12021: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12022: 			} elsif ( $internaltext =~ /\S/ ) {
                   12023: 		  # something interesting inside the tag
                   12024: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12025: 			} else {
1.908     albertel 12026: 		  # no interesting values, don't set a default
1.339     albertel 12027: 			}
1.172     www      12028: # end of not-a-package not-a-library import
1.339     albertel 12029: 		    }
1.172     www      12030: # end of not-a-package start tag
1.339     albertel 12031: 		}
1.172     www      12032: # the next is the end of "start tag"
1.339     albertel 12033: 	    }
                   12034: 	}
1.483     albertel 12035: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12036: 	$extension = lc($extension);
                   12037: 	if ($extension eq 'htm') { $extension='html'; }
                   12038: 
1.737     albertel 12039: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12040: 	    #no specific packages #how's our extension
                   12041: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12042: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12043: 					 \%metathesekeys);
                   12044: 	}
1.883     albertel 12045: 
                   12046: 	if (!exists($metaentry{':packages'})
                   12047: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12048: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12049: 		#no specific packages well let's get default then
                   12050: 		if ($key!~/^default&/) { next; }
1.488     albertel 12051: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12052: 					     \%metathesekeys);
                   12053: 	    }
                   12054: 	}
1.338     www      12055: # are there custom rights to evaluate
1.599     albertel 12056: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12057: 
1.338     www      12058:     #
                   12059:     # Importing a rights file here
1.339     albertel 12060:     #
                   12061: 	    unless ($depthcount) {
1.599     albertel 12062: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12063: 		my $dir=$filename;
                   12064: 		$dir=~s|[^/]*$||;
                   12065: 		$location=&filelocation($dir,$location);
1.736     albertel 12066: 		my $rights_metadata =
                   12067: 		    &metadata($uri,'keys',$location,'_rights',
                   12068: 			      $depthcount+1);
                   12069: 		foreach my $rights (split(',',$rights_metadata)) {
                   12070: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12071: 		    $metathesekeys{$rights}=1;
1.339     albertel 12072: 		}
                   12073: 	    }
                   12074: 	}
1.737     albertel 12075: 	# uniqifiy package listing
                   12076: 	my %seen;
                   12077: 	my @uniq_packages =
                   12078: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12079: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12080: 
1.1172.2.99  raeburn  12081:         if (($importedresponses) || ($importedparts)) {
                   12082:             if ($importedparts) {
1.1070    www      12083: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12084:                 $metaentry{':partorder'}='';
                   12085:                 $metathesekeys{'partorder'}=1;
                   12086:             }
                   12087:             if ($importedresponses) {
                   12088: # We had imported responses and need to rebuild responseorder
                   12089:                 $metaentry{':responseorder'}='';
                   12090:                 $metathesekeys{'responseorder'}=1;
                   12091:             }
                   12092:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12093:                 my $origid = $origfiletagids[$index+1];
                   12094:                 if ($origfiletagids[$index] eq 'part') {
                   12095: # Original part, part of the problem
                   12096:                     if ($importedparts) {
                   12097:                         $metaentry{':partorder'}.=','.$origid;
                   12098:                     }
                   12099:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12100:                     if ($importedparts) {
                   12101: # We have imported parts at this position
                   12102:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12103:                     }
                   12104:                     if ($importedresponses) {
                   12105: # We have imported responses at this position
                   12106:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12107:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12108:                         }
                   12109:                     }
                   12110:                 } else {
                   12111: # Original response item, part of the problem
                   12112:                     if ($importedresponses) {
                   12113:                         $metaentry{':responseorder'}.=','.$origid;
                   12114:                     }
                   12115:                 }
                   12116:             }
                   12117:             if ($importedparts) {
                   12118:                 $metaentry{':partorder'}=~s/^\,//;
                   12119:             }
                   12120:             if ($importedresponses) {
                   12121:                 $metaentry{':responseorder'}=~s/^\,//;
                   12122:             }
1.1070    www      12123:         }
                   12124: 
1.737     albertel 12125: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12126: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12127: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12128: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12129: # this is the end of "was not already recently cached
1.71      www      12130:     }
1.599     albertel 12131:     return $metaentry{':'.$what};
1.261     albertel 12132: }
                   12133: 
1.488     albertel 12134: sub metadata_create_package_def {
1.483     albertel 12135:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12136:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12137:     if ($subp eq 'default') { next; }
                   12138:     
1.599     albertel 12139:     if (defined($metaentry{':packages'})) {
                   12140: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12141:     } else {
1.599     albertel 12142: 	$metaentry{':packages'}=$package;
1.483     albertel 12143:     }
                   12144:     my $value=$packagetab{$key};
                   12145:     my $unikey;
                   12146:     $unikey='parameter_0_'.$name;
1.599     albertel 12147:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12148:     $$metathesekeys{$unikey}=1;
1.599     albertel 12149:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12150: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12151:     }
1.599     albertel 12152:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12153: 	$metaentry{':'.$unikey}=
                   12154: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12155:     }
                   12156: }
                   12157: 
1.261     albertel 12158: sub metadata_generate_part0 {
                   12159:     my ($metadata,$metacache,$uri) = @_;
                   12160:     my %allnames;
1.737     albertel 12161:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12162: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12163: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12164: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12165: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12166: 	    $allnames{$name}=$part;
                   12167: 	  }
                   12168: 	}
                   12169:     }
                   12170:     foreach my $name (keys(%allnames)) {
                   12171:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12172:       my $key=":parameter_0_$name";
1.261     albertel 12173:       $$metacache{"$key.part"}='0';
                   12174:       $$metacache{"$key.name"}=$name;
1.428     albertel 12175:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12176: 					   $allnames{$name}.'_'.$name.
                   12177: 					   '.type'};
1.428     albertel 12178:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12179: 			     '.display'};
1.644     www      12180:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12181:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12182:       $$metacache{"$key.display"}=$olddis;
                   12183:     }
1.71      www      12184: }
                   12185: 
1.764     albertel 12186: # ------------------------------------------------------ Devalidate title cache
                   12187: 
                   12188: sub devalidate_title_cache {
                   12189:     my ($url)=@_;
                   12190:     if (!$env{'request.course.id'}) { return; }
                   12191:     my $symb=&symbread($url);
                   12192:     if (!$symb) { return; }
                   12193:     my $key=$env{'request.course.id'}."\0".$symb;
                   12194:     &devalidate_cache_new('title',$key);
                   12195: }
                   12196: 
1.1014    droeschl 12197: # ------------------------------------------------- Get the title of a course
                   12198: 
                   12199: sub current_course_title {
                   12200:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12201: }
1.301     www      12202: # ------------------------------------------------- Get the title of a resource
                   12203: 
                   12204: sub gettitle {
                   12205:     my $urlsymb=shift;
                   12206:     my $symb=&symbread($urlsymb);
1.534     albertel 12207:     if ($symb) {
1.620     albertel 12208: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12209: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12210: 	if (defined($cached)) { 
                   12211: 	    return $result;
                   12212: 	}
1.534     albertel 12213: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12214: 	my $title='';
1.907     albertel 12215: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12216: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12217: 	} else {
                   12218: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12219: 		    &GDBM_READER(),0640)) {
                   12220: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12221: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12222: 		untie(%bighash);
                   12223: 	    }
1.534     albertel 12224: 	}
                   12225: 	$title=~s/\&colon\;/\:/gs;
                   12226: 	if ($title) {
1.1159    www      12227: # Remember both $symb and $title for dynamic metadata
                   12228:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12229:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12230: # Cache this title and then return it
1.599     albertel 12231: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12232: 	}
                   12233: 	$urlsymb=$url;
                   12234:     }
                   12235:     my $title=&metadata($urlsymb,'title');
                   12236:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12237:     return $title;
1.301     www      12238: }
1.613     albertel 12239: 
1.614     albertel 12240: sub get_slot {
                   12241:     my ($which,$cnum,$cdom)=@_;
                   12242:     if (!$cnum || !$cdom) {
1.790     albertel 12243: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12244: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12245: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12246:     }
1.703     albertel 12247:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12248:     my %slotinfo;
                   12249:     if (exists($remembered{$key})) {
                   12250: 	$slotinfo{$which} = $remembered{$key};
                   12251:     } else {
                   12252: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12253: 	&Apache::lonhomework::showhash(%slotinfo);
                   12254: 	my ($tmp)=keys(%slotinfo);
                   12255: 	if ($tmp=~/^error:/) { return (); }
                   12256: 	$remembered{$key} = $slotinfo{$which};
                   12257:     }
1.616     albertel 12258:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12259: 	return %{$slotinfo{$which}};
                   12260:     }
                   12261:     return $slotinfo{$which};
1.614     albertel 12262: }
1.1150    raeburn  12263: 
                   12264: sub get_reservable_slots {
                   12265:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12266:     my $now = time;
                   12267:     my $reservable_info;
                   12268:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12269:     if (exists($remembered{$key})) {
                   12270:         $reservable_info = $remembered{$key};
                   12271:     } else {
                   12272:         my %resv;
                   12273:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12274:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12275:         $reservable_info = \%resv;
                   12276:         $remembered{$key} = $reservable_info;
                   12277:     }
                   12278:     return $reservable_info;
                   12279: }
                   12280: 
                   12281: sub get_course_slots {
                   12282:     my ($cnum,$cdom) = @_;
                   12283:     my $hashid=$cnum.':'.$cdom;
                   12284:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12285:     if (defined($cached)) {
                   12286:         if (ref($result) eq 'HASH') {
                   12287:             return %{$result};
                   12288:         }
                   12289:     } else {
                   12290:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12291:         my ($tmp) = keys(%slots);
                   12292:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12293:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12294:             return %slots;
                   12295:         }
                   12296:     }
                   12297:     return;
                   12298: }
                   12299: 
                   12300: sub devalidate_slots_cache {
                   12301:     my ($cnum,$cdom)=@_;
                   12302:     my $hashid=$cnum.':'.$cdom;
                   12303:     &devalidate_cache_new('allslots',$hashid);
                   12304: }
                   12305: 
1.1172.2.8  raeburn  12306: sub get_coursechange {
                   12307:     my ($cdom,$cnum) = @_;
                   12308:     if ($cdom eq '' || $cnum eq '') {
                   12309:         return unless ($env{'request.course.id'});
                   12310:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12311:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12312:     }
                   12313:     my $hashid=$cdom.'_'.$cnum;
                   12314:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12315:     if ((defined($cached)) && ($change ne '')) {
                   12316:         return $change;
                   12317:     } else {
                   12318:         my %crshash;
                   12319:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12320:         if ($crshash{'internal.contentchange'} eq '') {
                   12321:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12322:             if ($change eq '') {
                   12323:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12324:                 $change = $crshash{'internal.created'};
                   12325:             }
                   12326:         } else {
                   12327:             $change = $crshash{'internal.contentchange'};
                   12328:         }
                   12329:         my $cachetime = 600;
                   12330:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12331:     }
                   12332:     return $change;
                   12333: }
                   12334: 
                   12335: sub devalidate_coursechange_cache {
                   12336:     my ($cnum,$cdom)=@_;
                   12337:     my $hashid=$cnum.':'.$cdom;
                   12338:     &devalidate_cache_new('crschange',$hashid);
                   12339: }
                   12340: 
1.31      www      12341: # ------------------------------------------------- Update symbolic store links
                   12342: 
                   12343: sub symblist {
                   12344:     my ($mapname,%newhash)=@_;
1.438     www      12345:     $mapname=&deversion(&declutter($mapname));
1.31      www      12346:     my %hash;
1.620     albertel 12347:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12348:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12349:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12350: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12351: 		next if ($url eq 'last_known'
                   12352: 			 && $env{'form.no_update_last_known'});
                   12353: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12354: 						    $newhash{$url}->[1],
                   12355: 						    $newhash{$url}->[0]);
1.191     harris41 12356:             }
1.31      www      12357:             if (untie(%hash)) {
                   12358: 		return 'ok';
                   12359:             }
                   12360:         }
                   12361:     }
                   12362:     return 'error';
1.212     www      12363: }
                   12364: 
                   12365: # --------------------------------------------------------------- Verify a symb
                   12366: 
                   12367: sub symbverify {
1.1172.2.11  raeburn  12368:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12369:     my $thisfn=$thisurl;
1.439     www      12370:     $thisfn=&declutter($thisfn);
1.215     www      12371: # direct jump to resource in page or to a sequence - will construct own symbs
                   12372:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12373: # check URL part
1.409     www      12374:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12375: 
1.431     www      12376:     unless ($url eq $thisfn) { return 0; }
1.213     www      12377: 
1.216     www      12378:     $symb=&symbclean($symb);
1.510     www      12379:     $thisurl=&deversion($thisurl);
1.439     www      12380:     $thisfn=&deversion($thisfn);
1.213     www      12381: 
                   12382:     my %bighash;
                   12383:     my $okay=0;
1.431     www      12384: 
1.620     albertel 12385:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12386:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12387:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12388:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12389:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12390:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12391:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12392:             }
                   12393:         }
                   12394:         my $ids;
1.1172.2.122  raeburn  12395:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12396:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12397:         } else {
                   12398:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12399:         }
1.1102    raeburn  12400:         unless ($ids) {
1.1172.2.13  raeburn  12401:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12402:             $ids=$bighash{$idkey};
1.216     www      12403:         }
                   12404:         if ($ids) {
                   12405: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12406:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12407:                 $symb =~ s/\?.+$//;
                   12408:             }
1.800     albertel 12409: 	    foreach my $id (split(/\,/,$ids)) {
                   12410: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12411:                if (
                   12412:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12413:    eq $symb) {
1.1172.2.11  raeburn  12414:                    if (ref($encstate)) {
                   12415:                        $$encstate = $bighash{'encrypted_'.$id};
                   12416:                    }
1.1172.2.13  raeburn  12417:                    if (($env{'request.role.adv'}) ||
                   12418:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12419:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12420:                        $okay=1;
                   12421:                        last;
                   12422:                    }
                   12423:                }
                   12424:            }
1.216     www      12425:         }
1.213     www      12426: 	untie(%bighash);
                   12427:     }
                   12428:     return $okay;
1.31      www      12429: }
                   12430: 
1.210     www      12431: # --------------------------------------------------------------- Clean-up symb
                   12432: 
                   12433: sub symbclean {
                   12434:     my $symb=shift;
1.568     albertel 12435:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12436: # remove version from map
                   12437:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12438: 
1.210     www      12439: # remove version from URL
                   12440:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12441: 
1.507     www      12442: # remove wrapper
                   12443: 
1.510     www      12444:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12445:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12446:     return $symb;
1.409     www      12447: }
                   12448: 
                   12449: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12450: 
                   12451: sub encode_symb {
                   12452:     my ($map,$resid,$url)=@_;
                   12453:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12454: }
1.409     www      12455: 
                   12456: sub decode_symb {
1.568     albertel 12457:     my $symb=shift;
                   12458:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12459:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12460:     return (&fixversion($map),$resid,&fixversion($url));
                   12461: }
                   12462: 
                   12463: sub fixversion {
                   12464:     my $fn=shift;
1.609     banghart 12465:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12466:     my %bighash;
                   12467:     my $uri=&clutter($fn);
1.620     albertel 12468:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12469: # is this cached?
1.599     albertel 12470:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12471:     if (defined($cached)) { return $result; }
                   12472: # unfortunately not cached, or expired
1.620     albertel 12473:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12474: 	    &GDBM_READER(),0640)) {
                   12475:  	if ($bighash{'version_'.$uri}) {
                   12476:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12477:  	    unless (($version eq 'mostrecent') || 
                   12478: 		    ($version==&getversion($uri))) {
1.440     www      12479:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12480:  	    }
                   12481:  	}
                   12482:  	untie %bighash;
1.413     www      12483:     }
1.599     albertel 12484:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12485: }
                   12486: 
                   12487: sub deversion {
                   12488:     my $url=shift;
                   12489:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12490:     return $url;
1.210     www      12491: }
                   12492: 
1.31      www      12493: # ------------------------------------------------------ Return symb list entry
                   12494: 
                   12495: sub symbread {
1.1172.2.126  raeburn  12496:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12497:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12498:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12499:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12500:         unless (ref($possibles) eq 'HASH') {
                   12501:             if ($ignorecachednull) {
                   12502:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12503:             } else {
                   12504:                 return $env{$cache_str};
                   12505:             }
1.1172.2.66  raeburn  12506:         }
                   12507:     }
1.242     www      12508: # no filename provided? try from environment
1.1172.2.54  raeburn  12509:     unless ($thisfn) {
1.620     albertel 12510:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  12511:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12512:         }
                   12513:         $thisfn=$env{'request.filename'};
1.44      www      12514:     }
1.569     albertel 12515:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12516: # is that filename actually a symb? Verify, clean, and return
                   12517:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12518: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  12519: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12520: 	}
1.242     www      12521:     }
1.44      www      12522:     $thisfn=declutter($thisfn);
1.31      www      12523:     my %hash;
1.37      www      12524:     my %bighash;
                   12525:     my $syval='';
1.620     albertel 12526:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12527:         my $targetfn = $thisfn;
1.609     banghart 12528:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12529:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12530:         }
1.687     albertel 12531: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12532: 	    $targetfn=$1;
                   12533: 	}
1.1172.2.128  raeburn  12534:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  12535:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12536:                           &GDBM_READER(),0640)) {
                   12537: 	        $syval=$hash{$targetfn};
                   12538:                 untie(%hash);
                   12539:             }
1.1172.2.128  raeburn  12540:             if ($syval && $checkforblock) {
                   12541:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  12542:                 if (@blockers) {
                   12543:                     $syval='';
                   12544:                 }
                   12545:             }
1.37      www      12546:         }
                   12547: # ---------------------------------------------------------- There was an entry
                   12548:         if ($syval) {
1.601     albertel 12549: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12550: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12551: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12552: 		    #return $env{$cache_str}='';
1.601     albertel 12553: 		#}    
                   12554: 		#$syval.=$1;
                   12555: 	    #}
1.37      www      12556:         } else {
                   12557: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12558:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12559:                             &GDBM_READER(),0640)) {
1.37      www      12560: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12561:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12562:               unless ($ids) { 
                   12563:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12564:               }
                   12565:               unless ($ids) {
                   12566: # alias?
                   12567: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12568:               }
1.37      www      12569:               if ($ids) {
                   12570: # ------------------------------------------------------------------- Has ID(s)
                   12571:                  my @possibilities=split(/\,/,$ids);
1.39      www      12572:                  if ($#possibilities==0) {
                   12573: # ----------------------------------------------- There is only one possibility
1.37      www      12574: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12575: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12576: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12577:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  12578:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12579:                              $possibles->{$syval} = 1;
                   12580:                          }
1.1172.2.66  raeburn  12581:                      }
                   12582:                      if ($checkforblock) {
1.1172.2.126  raeburn  12583:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  12584:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  12585:                              if (@blockers) {
                   12586:                                  $syval = '';
                   12587:                                  untie(%bighash);
                   12588:                                  return $env{$cache_str}='';
                   12589:                              }
1.1172.2.66  raeburn  12590:                          }
                   12591:                      }
                   12592:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12593: # ------------------------------------------ There is more than one possibility
                   12594:                      my $realpossible=0;
1.800     albertel 12595:                      foreach my $id (@possibilities) {
                   12596: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12597:                          my $canaccess;
                   12598:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12599:                              $canaccess = 1;
                   12600:                          } else {
                   12601:                              $canaccess = &allowed('bre',$file);
                   12602:                          }
                   12603:                          if ($canaccess) {
                   12604:          		     my ($mapid,$resid)=split(/\./,$id);
                   12605:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12606:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12607:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  12608:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  12609:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12610:                                  if ($checkforblock) {
1.1172.2.127  raeburn  12611:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  12612:                                      if (@blockers > 0) {
                   12613:                                          $syval = '';
                   12614:                                      } else {
1.1172.2.66  raeburn  12615:                                          $syval = $poss_syval;
                   12616:                                          $realpossible++;
                   12617:                                      }
                   12618:                                  } else {
                   12619:                                      $syval = $poss_syval;
                   12620:                                      $realpossible++;
                   12621:                                  }
1.1172.2.126  raeburn  12622:                                  if ($syval) {
                   12623:                                      if (ref($possibles) eq 'HASH') {
                   12624:                                          $possibles->{$syval} = 1;
                   12625:                                      }
                   12626:                                  }
1.1172.2.66  raeburn  12627:                              }
1.39      www      12628: 			 }
1.191     harris41 12629:                      }
1.39      www      12630: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12631:                  } else {
                   12632:                      $syval='';
1.37      www      12633:                  }
                   12634: 	      }
1.1172.2.66  raeburn  12635:               untie(%bighash);
1.481     raeburn  12636:            }
1.31      www      12637:         }
1.62      www      12638:         if ($syval) {
1.1172.2.128  raeburn  12639: 	    return $env{$cache_str}=$syval;
1.62      www      12640:         }
1.31      www      12641:     }
1.949     raeburn  12642:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12643:     return $env{$cache_str}='';
1.31      www      12644: }
                   12645: 
                   12646: # ---------------------------------------------------------- Return random seed
                   12647: 
1.32      www      12648: sub numval {
                   12649:     my $txt=shift;
                   12650:     $txt=~tr/A-J/0-9/;
                   12651:     $txt=~tr/a-j/0-9/;
                   12652:     $txt=~tr/K-T/0-9/;
                   12653:     $txt=~tr/k-t/0-9/;
                   12654:     $txt=~tr/U-Z/0-5/;
                   12655:     $txt=~tr/u-z/0-5/;
                   12656:     $txt=~s/\D//g;
1.564     albertel 12657:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12658:     return int($txt);
1.368     albertel 12659: }
                   12660: 
1.484     albertel 12661: sub numval2 {
                   12662:     my $txt=shift;
                   12663:     $txt=~tr/A-J/0-9/;
                   12664:     $txt=~tr/a-j/0-9/;
                   12665:     $txt=~tr/K-T/0-9/;
                   12666:     $txt=~tr/k-t/0-9/;
                   12667:     $txt=~tr/U-Z/0-5/;
                   12668:     $txt=~tr/u-z/0-5/;
                   12669:     $txt=~s/\D//g;
                   12670:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12671:     my $total;
                   12672:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12673:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12674:     return int($total);
                   12675: }
                   12676: 
1.575     albertel 12677: sub numval3 {
                   12678:     use integer;
                   12679:     my $txt=shift;
                   12680:     $txt=~tr/A-J/0-9/;
                   12681:     $txt=~tr/a-j/0-9/;
                   12682:     $txt=~tr/K-T/0-9/;
                   12683:     $txt=~tr/k-t/0-9/;
                   12684:     $txt=~tr/U-Z/0-5/;
                   12685:     $txt=~tr/u-z/0-5/;
                   12686:     $txt=~s/\D//g;
                   12687:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12688:     my $total;
                   12689:     foreach my $val (@txts) { $total+=$val; }
                   12690:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12691:     return $total;
                   12692: }
                   12693: 
1.675     albertel 12694: sub digest {
                   12695:     my ($data)=@_;
                   12696:     my $digest=&Digest::MD5::md5($data);
                   12697:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12698:     my ($e,$f);
                   12699:     {
                   12700:         use integer;
                   12701:         $e=($a+$b);
                   12702:         $f=($c+$d);
                   12703:         if ($_64bit) {
                   12704:             $e=(($e<<32)>>32);
                   12705:             $f=(($f<<32)>>32);
                   12706:         }
                   12707:     }
                   12708:     if (wantarray) {
                   12709: 	return ($e,$f);
                   12710:     } else {
                   12711: 	my $g;
                   12712: 	{
                   12713: 	    use integer;
                   12714: 	    $g=($e+$f);
                   12715: 	    if ($_64bit) {
                   12716: 		$g=(($g<<32)>>32);
                   12717: 	    }
                   12718: 	}
                   12719: 	return $g;
                   12720:     }
                   12721: }
                   12722: 
1.368     albertel 12723: sub latest_rnd_algorithm_id {
1.675     albertel 12724:     return '64bit5';
1.366     albertel 12725: }
1.32      www      12726: 
1.503     albertel 12727: sub get_rand_alg {
                   12728:     my ($courseid)=@_;
1.790     albertel 12729:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12730:     if ($courseid) {
1.620     albertel 12731: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12732:     }
                   12733:     return &latest_rnd_algorithm_id();
                   12734: }
                   12735: 
1.562     albertel 12736: sub validCODE {
                   12737:     my ($CODE)=@_;
                   12738:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12739:     return 0;
                   12740: }
                   12741: 
1.491     albertel 12742: sub getCODE {
1.620     albertel 12743:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12744:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12745: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12746: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12747: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12748:     }
                   12749:     return undef;
                   12750: }
1.1133    foxr     12751: #
                   12752: #  Determines the random seed for a specific context:
                   12753: #
                   12754: # parameters:
                   12755: #   symb      - in course context the symb for the seed.
                   12756: #   course_id - The course id of the form domain_coursenum.
                   12757: #   domain    - Domain for the user.
                   12758: #   course    - Course for the user.
                   12759: #   cenv      - environment of the course.
                   12760: #
                   12761: # NOTE:
                   12762: #   All parameters are picked out of the environment if missing
                   12763: #   or not defined.
                   12764: #   If a symb cannot be determined the current time is used instead.
                   12765: #
                   12766: #  For a given well defined symb, courside, domain, username,
                   12767: #  and course environment, the seed is reproducible.
                   12768: #
1.31      www      12769: sub rndseed {
1.1133    foxr     12770:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12771:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12772:     if (!defined($symb)) {
1.366     albertel 12773: 	unless ($symb=$wsymb) { return time; }
                   12774:     }
1.1146    foxr     12775:     if (!defined $courseid) { 
                   12776: 	$courseid=$wcourseid; 
                   12777:     }
                   12778:     if (!defined $domain) { $domain=$wdomain; }
                   12779:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12780: 
                   12781:     my $which;
                   12782:     if (defined($cenv->{'rndseed'})) {
                   12783: 	$which = $cenv->{'rndseed'};
                   12784:     } else {
                   12785: 	$which =&get_rand_alg($courseid);
                   12786:     }
1.491     albertel 12787:     if (defined(&getCODE())) {
1.675     albertel 12788: 	if ($which eq '64bit5') {
                   12789: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12790: 	} elsif ($which eq '64bit4') {
1.575     albertel 12791: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12792: 	} else {
                   12793: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12794: 	}
1.675     albertel 12795:     } elsif ($which eq '64bit5') {
                   12796: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12797:     } elsif ($which eq '64bit4') {
                   12798: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12799:     } elsif ($which eq '64bit3') {
                   12800: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12801:     } elsif ($which eq '64bit2') {
                   12802: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12803:     } elsif ($which eq '64bit') {
                   12804: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12805:     }
                   12806:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12807: }
                   12808: 
                   12809: sub rndseed_32bit {
                   12810:     my ($symb,$courseid,$domain,$username)=@_;
                   12811:     {
                   12812: 	use integer;
                   12813: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12814: 	my $symbseed=numval($symb) << 22;
                   12815: 	my $namechck=unpack("%32C*",$username) << 17;
                   12816: 	my $nameseed=numval($username) << 12;
                   12817: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12818: 	my $courseseed=unpack("%32C*",$courseid);
                   12819: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12820: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12821: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12822: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12823: 	return $num;
                   12824:     }
                   12825: }
                   12826: 
                   12827: sub rndseed_64bit {
                   12828:     my ($symb,$courseid,$domain,$username)=@_;
                   12829:     {
                   12830: 	use integer;
                   12831: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12832: 	my $symbseed=numval($symb) << 10;
                   12833: 	my $namechck=unpack("%32S*",$username);
                   12834: 	
                   12835: 	my $nameseed=numval($username) << 21;
                   12836: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12837: 	my $courseseed=unpack("%32S*",$courseid);
                   12838: 	
                   12839: 	my $num1=$symbchck+$symbseed+$namechck;
                   12840: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12841: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12842: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12843: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12844: 	return "$num1,$num2";
1.155     albertel 12845:     }
1.366     albertel 12846: }
                   12847: 
1.443     albertel 12848: sub rndseed_64bit2 {
                   12849:     my ($symb,$courseid,$domain,$username)=@_;
                   12850:     {
                   12851: 	use integer;
                   12852: 	# strings need to be an even # of cahracters long, it it is odd the
                   12853:         # last characters gets thrown away
                   12854: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12855: 	my $symbseed=numval($symb) << 10;
                   12856: 	my $namechck=unpack("%32S*",$username.' ');
                   12857: 	
                   12858: 	my $nameseed=numval($username) << 21;
1.501     albertel 12859: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12860: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12861: 	
                   12862: 	my $num1=$symbchck+$symbseed+$namechck;
                   12863: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12864: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12865: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12866: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12867: 	return "$num1,$num2";
                   12868:     }
                   12869: }
                   12870: 
                   12871: sub rndseed_64bit3 {
                   12872:     my ($symb,$courseid,$domain,$username)=@_;
                   12873:     {
                   12874: 	use integer;
                   12875: 	# strings need to be an even # of cahracters long, it it is odd the
                   12876:         # last characters gets thrown away
                   12877: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12878: 	my $symbseed=numval2($symb) << 10;
                   12879: 	my $namechck=unpack("%32S*",$username.' ');
                   12880: 	
                   12881: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12882: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12883: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12884: 	
                   12885: 	my $num1=$symbchck+$symbseed+$namechck;
                   12886: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12887: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12888: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12889: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12890: 	
1.503     albertel 12891: 	return "$num1:$num2";
1.443     albertel 12892:     }
                   12893: }
                   12894: 
1.575     albertel 12895: sub rndseed_64bit4 {
                   12896:     my ($symb,$courseid,$domain,$username)=@_;
                   12897:     {
                   12898: 	use integer;
                   12899: 	# strings need to be an even # of cahracters long, it it is odd the
                   12900:         # last characters gets thrown away
                   12901: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12902: 	my $symbseed=numval3($symb) << 10;
                   12903: 	my $namechck=unpack("%32S*",$username.' ');
                   12904: 	
                   12905: 	my $nameseed=numval3($username) << 21;
                   12906: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12907: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12908: 	
                   12909: 	my $num1=$symbchck+$symbseed+$namechck;
                   12910: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12911: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12912: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12913: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12914: 	
1.575     albertel 12915: 	return "$num1:$num2";
                   12916:     }
                   12917: }
                   12918: 
1.675     albertel 12919: sub rndseed_64bit5 {
                   12920:     my ($symb,$courseid,$domain,$username)=@_;
                   12921:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12922:     return "$num1:$num2";
                   12923: }
                   12924: 
1.366     albertel 12925: sub rndseed_CODE_64bit {
                   12926:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12927:     {
1.366     albertel 12928: 	use integer;
1.443     albertel 12929: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12930: 	my $symbseed=numval2($symb);
1.491     albertel 12931: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12932: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12933: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12934: 	my $num1=$symbseed+$CODEchck;
                   12935: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12936: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12937: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12938: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12939: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12940: 	return "$num1:$num2";
1.366     albertel 12941:     }
                   12942: }
                   12943: 
1.575     albertel 12944: sub rndseed_CODE_64bit4 {
                   12945:     my ($symb,$courseid,$domain,$username)=@_;
                   12946:     {
                   12947: 	use integer;
                   12948: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12949: 	my $symbseed=numval3($symb);
                   12950: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12951: 	my $CODEseed=numval3(&getCODE());
                   12952: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12953: 	my $num1=$symbseed+$CODEchck;
                   12954: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12955: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12956: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12957: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12958: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12959: 	return "$num1:$num2";
                   12960:     }
                   12961: }
                   12962: 
1.675     albertel 12963: sub rndseed_CODE_64bit5 {
                   12964:     my ($symb,$courseid,$domain,$username)=@_;
                   12965:     my $code = &getCODE();
                   12966:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12967:     return "$num1:$num2";
                   12968: }
                   12969: 
1.366     albertel 12970: sub setup_random_from_rndseed {
                   12971:     my ($rndseed)=@_;
1.503     albertel 12972:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12973: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12974:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12975:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12976:         } else {
                   12977:             &Math::Random::random_set_seed($num1,$num2);
                   12978:         }
1.366     albertel 12979:     } else {
                   12980: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12981:     }
1.36      albertel 12982: }
                   12983: 
1.474     albertel 12984: sub latest_receipt_algorithm_id {
1.835     albertel 12985:     return 'receipt3';
1.474     albertel 12986: }
                   12987: 
1.480     www      12988: sub recunique {
                   12989:     my $fucourseid=shift;
                   12990:     my $unique;
1.835     albertel 12991:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12992: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12993: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12994:     } else {
                   12995: 	$unique=$perlvar{'lonReceipt'};
                   12996:     }
                   12997:     return unpack("%32C*",$unique);
                   12998: }
                   12999: 
                   13000: sub recprefix {
                   13001:     my $fucourseid=shift;
                   13002:     my $prefix;
1.835     albertel 13003:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13004: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13005: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13006:     } else {
                   13007: 	$prefix=$perlvar{'lonHostID'};
                   13008:     }
                   13009:     return unpack("%32C*",$prefix);
                   13010: }
                   13011: 
1.76      www      13012: sub ireceipt {
1.474     albertel 13013:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13014: 
                   13015:     my $return =&recprefix($fucourseid).'-';
                   13016: 
                   13017:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13018: 	$env{'request.state'} eq 'construct') {
                   13019: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13020: 	return $return;
                   13021:     }
                   13022: 
1.76      www      13023:     my $cuname=unpack("%32C*",$funame);
                   13024:     my $cudom=unpack("%32C*",$fudom);
                   13025:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13026:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13027:     my $cunique=&recunique($fucourseid);
1.474     albertel 13028:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13029:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13030: 
1.790     albertel 13031: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13032: 			       
                   13033: 	$return.= ($cunique%$cuname+
                   13034: 		   $cunique%$cudom+
                   13035: 		   $cusymb%$cuname+
                   13036: 		   $cusymb%$cudom+
                   13037: 		   $cucourseid%$cuname+
                   13038: 		   $cucourseid%$cudom+
                   13039: 		   $cpart%$cuname+
                   13040: 		   $cpart%$cudom);
                   13041:     } else {
                   13042: 	$return.= ($cunique%$cuname+
                   13043: 		   $cunique%$cudom+
                   13044: 		   $cusymb%$cuname+
                   13045: 		   $cusymb%$cudom+
                   13046: 		   $cucourseid%$cuname+
                   13047: 		   $cucourseid%$cudom);
                   13048:     }
                   13049:     return $return;
1.76      www      13050: }
                   13051: 
                   13052: sub receipt {
1.474     albertel 13053:     my ($part)=@_;
1.790     albertel 13054:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13055:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13056: }
1.260     ng       13057: 
1.790     albertel 13058: sub whichuser {
                   13059:     my ($passedsymb)=@_;
                   13060:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13061:     if (defined($env{'form.grade_symb'})) {
                   13062: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13063: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13064: 	if (!$allowed &&
                   13065: 	    exists($env{'request.course.sec'}) &&
                   13066: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13067: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13068: 			      '/'.$env{'request.course.sec'});
                   13069: 	}
                   13070: 	if ($allowed) {
                   13071: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13072: 	    $courseid=$tmp_courseid;
                   13073: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13074: 	    ($name)=&get_env_multiple('form.grade_username');
                   13075: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13076: 	}
                   13077:     }
                   13078:     if (!$passedsymb) {
                   13079: 	$symb=&symbread();
                   13080:     } else {
                   13081: 	$symb=$passedsymb;
                   13082:     }
                   13083:     $courseid=$env{'request.course.id'};
                   13084:     $domain=$env{'user.domain'};
                   13085:     $name=$env{'user.name'};
                   13086:     if ($name eq 'public' && $domain eq 'public') {
                   13087: 	if (!defined($env{'form.username'})) {
                   13088: 	    $env{'form.username'}.=time.rand(10000000);
                   13089: 	}
                   13090: 	$name.=$env{'form.username'};
                   13091:     }
                   13092:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13093: 
                   13094: }
                   13095: 
1.36      albertel 13096: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13097: # returns either the contents of the file or 
                   13098: # -1 if the file doesn't exist
1.481     raeburn  13099: #
                   13100: # if the target is a file that was uploaded via DOCS, 
                   13101: # a check will be made to see if a current copy exists on the local server,
                   13102: # if it does this will be served, otherwise a copy will be retrieved from
                   13103: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13104: # the local server.   
1.472     albertel 13105: 
1.36      albertel 13106: sub getfile {
1.538     albertel 13107:     my ($file) = @_;
1.609     banghart 13108:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13109:     &repcopy($file);
                   13110:     return &readfile($file);
                   13111: }
                   13112: 
                   13113: sub repcopy_userfile {
                   13114:     my ($file)=@_;
1.1142    raeburn  13115:     my $londocroot = $perlvar{'lonDocRoot'};
                   13116:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13117:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13118:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13119: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13120:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13121:     if (-e "$file") {
1.828     www      13122: # we already have a local copy, check it out
1.538     albertel 13123: 	my @fileinfo = stat($file);
1.828     www      13124: 	my $rtncode;
                   13125: 	my $info;
1.538     albertel 13126: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13127: 	if ($lwpresp ne 'ok') {
1.828     www      13128: # there is no such file anymore, even though we had a local copy
1.482     albertel 13129: 	    if ($rtncode eq '404') {
1.538     albertel 13130: 		unlink($file);
1.482     albertel 13131: 	    }
                   13132: 	    return -1;
                   13133: 	}
                   13134: 	if ($info < $fileinfo[9]) {
1.828     www      13135: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13136: 	    return 'ok';
1.828     www      13137: 	} else {
                   13138: # the file is outdated, get rid of it
                   13139: 	    unlink($file);
1.482     albertel 13140: 	}
1.828     www      13141:     }
                   13142: # one way or the other, at this point, we don't have the file
                   13143: # construct the correct path for the file
                   13144:     my @parts = ($cdom,$cnum); 
                   13145:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13146: 	push @parts, split(/\//,$1);
                   13147:     }
                   13148:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13149:     foreach my $part (@parts) {
                   13150: 	$path .= '/'.$part;
                   13151: 	if (!-e $path) {
                   13152: 	    mkdir($path,0770);
1.482     albertel 13153: 	}
                   13154:     }
1.828     www      13155: # now the path exists for sure
                   13156: # get a user agent
                   13157:     my $ua=new LWP::UserAgent;
                   13158:     my $transferfile=$file.'.in.transfer';
                   13159: # FIXME: this should flock
                   13160:     if (-e $transferfile) { return 'ok'; }
                   13161:     my $request;
                   13162:     $uri=~s/^\///;
1.980     raeburn  13163:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13164:     my $hostname = &hostname($homeserver);
1.980     raeburn  13165:     my $protocol = $protocol{$homeserver};
                   13166:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13167:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13168:     my $response=$ua->request($request,$transferfile);
                   13169: # did it work?
                   13170:     if ($response->is_error()) {
                   13171: 	unlink($transferfile);
                   13172: 	&logthis("Userfile repcopy failed for $uri");
                   13173: 	return -1;
                   13174:     }
                   13175: # worked, rename the transfer file
                   13176:     rename($transferfile,$file);
1.607     raeburn  13177:     return 'ok';
1.481     raeburn  13178: }
                   13179: 
1.517     albertel 13180: sub tokenwrapper {
                   13181:     my $uri=shift;
1.980     raeburn  13182:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13183:     $uri=~s|^/||;
1.620     albertel 13184:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13185:     my $token=$1;
1.552     albertel 13186:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13187:     if ($udom && $uname && $file) {
                   13188: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13189:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13190:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13191:         my $hostname = &hostname($homeserver);
1.980     raeburn  13192:         my $protocol = $protocol{$homeserver};
                   13193:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13194:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13195:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13196:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13197:     } else {
                   13198:         return '/adm/notfound.html';
                   13199:     }
                   13200: }
                   13201: 
1.828     www      13202: # call with reqtype HEAD: get last modification time
                   13203: # call with reqtype GET: get the file contents
                   13204: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13205: #
1.481     raeburn  13206: sub getuploaded {
                   13207:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13208:     $uri=~s/^\///;
1.980     raeburn  13209:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13210:     my $hostname = &hostname($homeserver);
1.980     raeburn  13211:     my $protocol = $protocol{$homeserver};
                   13212:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13213:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13214:     my $ua=new LWP::UserAgent;
                   13215:     my $request=new HTTP::Request($reqtype,$uri);
                   13216:     my $response=$ua->request($request);
                   13217:     $$rtncode = $response->code;
1.482     albertel 13218:     if (! $response->is_success()) {
                   13219: 	return 'failed';
                   13220:     }      
                   13221:     if ($reqtype eq 'HEAD') {
1.486     www      13222: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13223:     } elsif ($reqtype eq 'GET') {
                   13224: 	$$info = $response->content;
1.472     albertel 13225:     }
1.482     albertel 13226:     return 'ok';
1.36      albertel 13227: }
                   13228: 
1.481     raeburn  13229: sub readfile {
                   13230:     my $file = shift;
                   13231:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13232:     my $fh;
1.1172.2.96  raeburn  13233:     open($fh,"<",$file);
1.481     raeburn  13234:     my $a='';
1.800     albertel 13235:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13236:     return $a;
                   13237: }
                   13238: 
1.36      albertel 13239: sub filelocation {
1.590     banghart 13240:     my ($dir,$file) = @_;
                   13241:     my $location;
                   13242:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13243: 
                   13244:     if ($file =~ m-^/adm/-) {
                   13245: 	$file=~s-^/adm/wrapper/-/-;
                   13246: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13247:     }
1.882     albertel 13248: 
1.1139    www      13249:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13250:         $location = $file;
1.609     banghart 13251:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13252:         my ($udom,$uname,$filename)=
1.811     albertel 13253:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13254:         my $home=&homeserver($uname,$udom);
                   13255:         my $is_me=0;
                   13256:         my @ids=&current_machine_ids();
                   13257:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13258:         if ($is_me) {
1.1117    foxr     13259:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13260:         } else {
                   13261:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13262:   	      $udom.'/'.$uname.'/'.$filename;
                   13263:         }
1.882     albertel 13264:     } elsif ($file =~ m-^/adm/-) {
                   13265: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13266:     } else {
                   13267:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13268:         $file=~s:^/(res|priv)/:/:;
                   13269:         my $space=$1;
1.590     banghart 13270:         if ( !( $file =~ m:^/:) ) {
                   13271:             $location = $dir. '/'.$file;
                   13272:         } else {
1.1142    raeburn  13273:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13274:         }
1.59      albertel 13275:     }
1.590     banghart 13276:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13277:     while ($location=~m{/\.\./}) {
                   13278: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13279: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13280: 	} else {
                   13281: 	    $location=~ s{/\.\./}{/}g;
                   13282: 	}
                   13283:     } #remove dir/..
1.590     banghart 13284:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13285:     return $location;
1.46      www      13286: }
1.36      albertel 13287: 
1.46      www      13288: sub hreflocation {
                   13289:     my ($dir,$file)=@_;
1.980     raeburn  13290:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13291: 	$file=filelocation($dir,$file);
1.700     albertel 13292:     } elsif ($file=~m-^/adm/-) {
                   13293: 	$file=~s-^/adm/wrapper/-/-;
                   13294: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13295:     }
                   13296:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13297: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13298:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13299: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13300: 	        {/uploaded/$1/$2/}x;
1.46      www      13301:     }
1.913     albertel 13302:     if ($file=~ m{^/userfiles/}) {
                   13303: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13304:     }
1.462     albertel 13305:     return $file;
1.465     albertel 13306: }
                   13307: 
1.1139    www      13308: 
                   13309: 
                   13310: 
                   13311: 
1.465     albertel 13312: sub current_machine_domains {
1.853     albertel 13313:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13314: }
                   13315: 
                   13316: sub machine_domains {
                   13317:     my ($hostname) = @_;
1.465     albertel 13318:     my @domains;
1.838     albertel 13319:     my %hostname = &all_hostnames();
1.465     albertel 13320:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13321: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13322: 	if ($hostname eq $name) {
1.844     albertel 13323: 	    push(@domains,&host_domain($id));
1.465     albertel 13324: 	}
                   13325:     }
                   13326:     return @domains;
                   13327: }
                   13328: 
                   13329: sub current_machine_ids {
1.853     albertel 13330:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13331: }
                   13332: 
                   13333: sub machine_ids {
                   13334:     my ($hostname) = @_;
                   13335:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13336:     my @ids;
1.888     albertel 13337:     my %name_to_host = &all_names();
1.889     albertel 13338:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13339: 	return @{ $name_to_host{$hostname} };
                   13340:     }
                   13341:     return;
1.31      www      13342: }
                   13343: 
1.824     raeburn  13344: sub additional_machine_domains {
                   13345:     my @domains;
1.1172.2.96  raeburn  13346:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13347:     while( my $line = <$fh>) {
                   13348:         $line =~ s/\s//g;
                   13349:         push(@domains,$line);
                   13350:     }
                   13351:     return @domains;
                   13352: }
                   13353: 
                   13354: sub default_login_domain {
                   13355:     my $domain = $perlvar{'lonDefDomain'};
                   13356:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13357:     foreach my $posdom (&current_machine_domains(),
                   13358:                         &additional_machine_domains()) {
                   13359:         if (lc($posdom) eq lc($testdomain)) {
                   13360:             $domain=$posdom;
                   13361:             last;
                   13362:         }
                   13363:     }
                   13364:     return $domain;
                   13365: }
                   13366: 
1.1172.2.106  raeburn  13367: sub shared_institution {
1.1172.2.136  raeburn  13368:     my ($dom,$lonhost) = @_;
                   13369:     if ($lonhost eq '') {
                   13370:         $lonhost = $perlvar{'lonHostID'};
                   13371:     }
1.1172.2.106  raeburn  13372:     my $same_intdom;
1.1172.2.136  raeburn  13373:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13374:     if ($hostintdom ne '') {
                   13375:         my %iphost = &get_iphost();
                   13376:         my $primary_id = &domain($dom,'primary');
                   13377:         my $primary_ip = &get_host_ip($primary_id);
                   13378:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13379:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13380:                 my $intdom = &internet_dom($id);
                   13381:                 if ($intdom eq $hostintdom) {
                   13382:                     $same_intdom = 1;
                   13383:                     last;
                   13384:                 }
                   13385:             }
                   13386:         }
                   13387:     }
                   13388:     return $same_intdom;
                   13389: }
                   13390: 
1.1172.2.120  raeburn  13391: sub uses_sts {
                   13392:     my ($ignore_cache) = @_;
                   13393:     my $lonhost = $perlvar{'lonHostID'};
                   13394:     my $hostname = &hostname($lonhost);
                   13395:     my $sts_on;
                   13396:     if ($protocol{$lonhost} eq 'https') {
                   13397:         my $cachetime = 12*3600;
                   13398:         if (!$ignore_cache) {
                   13399:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13400:             if (defined($cached)) {
                   13401:                 return $sts_on;
                   13402:             }
                   13403:         }
1.1172.2.121  raeburn  13404:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13405:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13406:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13407:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13408:         if ($response->is_success) {
                   13409:             my $has_sts = $response->header('Strict-Transport-Security');
                   13410:             if ($has_sts eq '') {
                   13411:                 $sts_on = 0;
                   13412:             } else {
                   13413:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13414:                     my $maxage = $1;
                   13415:                     if ($maxage) {
                   13416:                         $sts_on = 1;
                   13417:                     } else {
                   13418:                         $sts_on = 0;
                   13419:                     }
                   13420:                 } else {
                   13421:                     $sts_on = 0;
                   13422:                 }
                   13423:             }
                   13424:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13425:         }
                   13426:     }
                   13427:     return;
                   13428: }
                   13429: 
1.1172.2.134  raeburn  13430: sub get_requestor_ip {
                   13431:     my ($r,$nolookup,$noproxy) = @_;
                   13432:     my $from_ip;
                   13433:     if (ref($r)) {
                   13434:         $from_ip = $r->get_remote_host($nolookup);
                   13435:     } else {
                   13436:         $from_ip = $ENV{'REMOTE_ADDR'};
                   13437:     }
                   13438:     return $from_ip;
                   13439: }
                   13440: 
1.31      www      13441: # ------------------------------------------------------------- Declutters URLs
                   13442: 
                   13443: sub declutter {
                   13444:     my $thisfn=shift;
1.569     albertel 13445:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13446:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13447:         $thisfn=~s{^/home/httpd/html}{};
                   13448:     }
1.31      www      13449:     $thisfn=~s/^\///;
1.697     albertel 13450:     $thisfn=~s|^adm/wrapper/||;
                   13451:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13452:     $thisfn=~s/^res\///;
1.1172    bisitz   13453:     $thisfn=~s/^priv\///;
1.1032    raeburn  13454:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13455:         $thisfn=~s/\?.+$//;
                   13456:     }
1.268     www      13457:     return $thisfn;
                   13458: }
                   13459: 
                   13460: # ------------------------------------------------------------- Clutter up URLs
                   13461: 
                   13462: sub clutter {
                   13463:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13464:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13465: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13466:        $thisfn='/res'.$thisfn; 
                   13467:     }
1.1031    raeburn  13468:     if ($thisfn !~m|^/adm|) {
                   13469: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13470: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13471: 	} else {
                   13472: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13473: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13474: 	    if ($embstyle eq 'ssi'
                   13475: 		|| ($embstyle eq 'hdn')
                   13476: 		|| ($embstyle eq 'rat')
                   13477: 		|| ($embstyle eq 'prv')
                   13478: 		|| ($embstyle eq 'ign')) {
                   13479: 		#do nothing with these
                   13480: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13481: 		|| ($embstyle eq 'emb')
                   13482: 		|| ($embstyle eq 'wrp')) {
                   13483: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13484: 	    } elsif ($embstyle eq 'unk'
                   13485: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13486: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13487: 	    } else {
1.718     www      13488: #		&logthis("Got a blank emb style");
1.695     albertel 13489: 	    }
1.694     albertel 13490: 	}
                   13491:     }
1.31      www      13492:     return $thisfn;
1.12      www      13493: }
                   13494: 
1.787     albertel 13495: sub clutter_with_no_wrapper {
                   13496:     my $uri = &clutter(shift);
                   13497:     if ($uri =~ m-^/adm/-) {
                   13498: 	$uri =~ s-^/adm/wrapper/-/-;
                   13499: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13500:     }
                   13501:     return $uri;
                   13502: }
                   13503: 
1.557     albertel 13504: sub freeze_escape {
                   13505:     my ($value)=@_;
                   13506:     if (ref($value)) {
                   13507: 	$value=&nfreeze($value);
                   13508: 	return '__FROZEN__'.&escape($value);
                   13509:     }
                   13510:     return &escape($value);
                   13511: }
                   13512: 
1.11      www      13513: 
1.557     albertel 13514: sub thaw_unescape {
                   13515:     my ($value)=@_;
                   13516:     if ($value =~ /^__FROZEN__/) {
                   13517: 	substr($value,0,10,undef);
                   13518: 	$value=&unescape($value);
                   13519: 	return &thaw($value);
                   13520:     }
                   13521:     return &unescape($value);
                   13522: }
                   13523: 
1.436     albertel 13524: sub correct_line_ends {
                   13525:     my ($result)=@_;
                   13526:     $$result =~s/\r\n/\n/mg;
                   13527:     $$result =~s/\r/\n/mg;
1.415     albertel 13528: }
1.1       albertel 13529: # ================================================================ Main Program
                   13530: 
1.184     www      13531: sub goodbye {
1.204     albertel 13532:    &logthis("Starting Shut down");
1.443     albertel 13533: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13534:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13535: #converted
1.599     albertel 13536: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13537:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13538: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13539: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13540: #1.1 only
1.870     albertel 13541: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13542: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13543: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13544: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13545:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13546:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13547:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13548:    &flushcourselogs();
                   13549:    &logthis("Shutting down");
                   13550: }
                   13551: 
1.852     albertel 13552: sub get_dns {
1.1172.2.17  raeburn  13553:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13554:     if (!$ignore_cache) {
                   13555: 	my ($content,$cached)=
                   13556: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13557: 	if ($cached) {
1.1172.2.17  raeburn  13558: 	    &$func($content,$hashref);
1.869     albertel 13559: 	    return;
                   13560: 	}
                   13561:     }
                   13562: 
                   13563:     my %alldns;
1.1172.2.96  raeburn  13564:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13565:         foreach my $dns (<$config>) {
                   13566: 	    next if ($dns !~ /^\^(\S*)/x);
                   13567:             my $line = $1;
                   13568:             my ($host,$protocol) = split(/:/,$line);
                   13569:             if ($protocol ne 'https') {
                   13570:                 $protocol = 'http';
                   13571:             }
                   13572: 	    $alldns{$host} = $protocol;
1.979     raeburn  13573:         }
1.1172.2.96  raeburn  13574:         close($config);
1.869     albertel 13575:     }
                   13576:     while (%alldns) {
1.1172.2.52  raeburn  13577: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13578: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13579:         $ua->timeout(30);
1.979     raeburn  13580: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13581: 	my $response=$ua->request($request);
1.979     raeburn  13582:         delete($alldns{$dns});
1.852     albertel 13583: 	next if ($response->is_error());
                   13584: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13585:         unless ($nocache) {
1.1172.2.23  raeburn  13586: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13587:         }
                   13588: 	&$func(\@content,$hashref);
1.869     albertel 13589: 	return;
1.852     albertel 13590:     }
1.871     albertel 13591:     my $which = (split('/',$url))[3];
                   13592:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13593:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13594:         my @content = <$config>;
                   13595:         &$func(\@content,$hashref);
                   13596:     }
1.1172.2.17  raeburn  13597:     return;
                   13598: }
                   13599: 
                   13600: # ------------------------------------------------------Get DNS checksums file
                   13601: sub parse_dns_checksums_tab {
                   13602:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13603:     my $lonhost = $perlvar{'lonHostID'};
                   13604:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13605:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13606:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13607:     my $webconfdir = '/etc/httpd/conf';
                   13608:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13609:         $webconfdir = '/etc/apache2';
                   13610:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13611:         if ($1 >= 10) {
                   13612:             $webconfdir = '/etc/apache2';
                   13613:         }
                   13614:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13615:         if ($1 >= 10.0) {
                   13616:             $webconfdir = '/etc/apache2';
                   13617:         }
                   13618:     }
1.1172.2.17  raeburn  13619:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13620:     my (%chksum,%revnum);
                   13621:     if (ref($lines) eq 'ARRAY') {
                   13622:         chomp(@{$lines});
1.1172.2.34  raeburn  13623:         my $version = shift(@{$lines});
                   13624:         if ($version eq $release) {
1.1172.2.17  raeburn  13625:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13626:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13627:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13628:                     if ($webconfdir eq '/etc/apache2') {
                   13629:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13630:                     }
                   13631:                 }
1.1172.2.34  raeburn  13632:                 $chksum{$file} = $shasum;
                   13633:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13634:             }
                   13635:             if (ref($hashref) eq 'HASH') {
                   13636:                 %{$hashref} = (
                   13637:                                 sums     => \%chksum,
                   13638:                                 versions => \%revnum,
                   13639:                               );
                   13640:             }
                   13641:         }
                   13642:     }
1.869     albertel 13643:     return;
1.852     albertel 13644: }
1.1172.2.17  raeburn  13645: 
                   13646: sub fetch_dns_checksums {
                   13647:     my %checksums;
1.1172.2.34  raeburn  13648:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13649:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13650:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13651:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13652:              \%checksums);
                   13653:     return \%checksums;
                   13654: }
                   13655: 
1.327     albertel 13656: # ------------------------------------------------------------ Read domain file
                   13657: {
1.852     albertel 13658:     my $loaded;
1.846     albertel 13659:     my %domain;
                   13660: 
1.852     albertel 13661:     sub parse_domain_tab {
                   13662: 	my ($lines) = @_;
                   13663: 	foreach my $line (@$lines) {
                   13664: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13665: 
1.846     albertel 13666: 	    chomp($line);
1.852     albertel 13667: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13668: 	    my %this_domain;
                   13669: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13670: 			       'lang_def', 'city', 'longi', 'lati',
                   13671: 			       'primary') {
                   13672: 		$this_domain{$field} = shift(@elements);
                   13673: 	    }
                   13674: 	    $domain{$name} = \%this_domain;
1.852     albertel 13675: 	}
                   13676:     }
1.864     albertel 13677: 
                   13678:     sub reset_domain_info {
                   13679: 	undef($loaded);
                   13680: 	undef(%domain);
                   13681:     }
                   13682: 
1.852     albertel 13683:     sub load_domain_tab {
1.1172.2.70  raeburn  13684: 	my ($ignore_cache,$nocache) = @_;
                   13685: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13686: 	my $fh;
1.1172.2.96  raeburn  13687: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13688: 	    my @lines = <$fh>;
                   13689: 	    &parse_domain_tab(\@lines);
1.448     albertel 13690: 	}
1.852     albertel 13691: 	close($fh);
                   13692: 	$loaded = 1;
1.327     albertel 13693:     }
1.846     albertel 13694: 
                   13695:     sub domain {
1.852     albertel 13696: 	&load_domain_tab() if (!$loaded);
                   13697: 
1.846     albertel 13698: 	my ($name,$what) = @_;
                   13699: 	return if ( !exists($domain{$name}) );
                   13700: 
                   13701: 	if (!$what) {
                   13702: 	    return $domain{$name}{'description'};
                   13703: 	}
                   13704: 	return $domain{$name}{$what};
                   13705:     }
1.974     raeburn  13706: 
                   13707:     sub domain_info {
                   13708:         &load_domain_tab() if (!$loaded);
                   13709:         return %domain;
                   13710:     }
                   13711: 
1.327     albertel 13712: }
                   13713: 
                   13714: 
1.1       albertel 13715: # ------------------------------------------------------------- Read hosts file
                   13716: {
1.838     albertel 13717:     my %hostname;
1.844     albertel 13718:     my %hostdom;
1.845     albertel 13719:     my %libserv;
1.852     albertel 13720:     my $loaded;
1.888     albertel 13721:     my %name_to_host;
1.1074    raeburn  13722:     my %internetdom;
1.1107    raeburn  13723:     my %LC_dns_serv;
1.852     albertel 13724: 
                   13725:     sub parse_hosts_tab {
                   13726: 	my ($file) = @_;
                   13727: 	foreach my $configline (@$file) {
                   13728: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13729:             chomp($configline);
                   13730: 	    if ($configline =~ /^\^/) {
                   13731:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13732:                     $LC_dns_serv{$1} = 1;
                   13733:                 }
                   13734:                 next;
                   13735:             }
1.1074    raeburn  13736: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13737: 	    $name=~s/\s//g;
                   13738: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13739:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13740:                     my $curr = $hostname{$id};
                   13741:                     my $skip;
                   13742:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13743:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13744:                             $skip = 1;
                   13745:                         } else {
                   13746:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13747:                         }
                   13748:                     }
                   13749:                     unless ($skip) {
                   13750:                         push(@{$name_to_host{$name}},$id);
                   13751:                     }
                   13752:                 } else {
                   13753:                     push(@{$name_to_host{$name}},$id);
                   13754:                 }
1.852     albertel 13755: 		$hostname{$id}=$name;
                   13756: 		$hostdom{$id}=$domain;
                   13757: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13758:                 if (defined($protocol)) {
                   13759:                     if ($protocol eq 'https') {
                   13760:                         $protocol{$id} = $protocol;
                   13761:                     } else {
                   13762:                         $protocol{$id} = 'http'; 
                   13763:                     }
1.968     raeburn  13764:                 } else {
1.969     raeburn  13765:                     $protocol{$id} = 'http';
1.968     raeburn  13766:                 }
1.1074    raeburn  13767:                 if (defined($intdom)) {
                   13768:                     $internetdom{$id} = $intdom;
                   13769:                 }
1.852     albertel 13770: 	    }
                   13771: 	}
                   13772:     }
1.864     albertel 13773:     
                   13774:     sub reset_hosts_info {
1.897     albertel 13775: 	&purge_remembered();
1.864     albertel 13776: 	&reset_domain_info();
                   13777: 	&reset_hosts_ip_info();
1.892     albertel 13778: 	undef(%name_to_host);
1.864     albertel 13779: 	undef(%hostname);
                   13780: 	undef(%hostdom);
                   13781: 	undef(%libserv);
                   13782: 	undef($loaded);
                   13783:     }
1.1       albertel 13784: 
1.852     albertel 13785:     sub load_hosts_tab {
1.1172.2.70  raeburn  13786: 	my ($ignore_cache,$nocache) = @_;
                   13787: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13788: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13789: 	my @config = <$config>;
                   13790: 	&parse_hosts_tab(\@config);
                   13791: 	close($config);
                   13792: 	$loaded=1;
1.1       albertel 13793:     }
1.852     albertel 13794: 
1.838     albertel 13795:     sub hostname {
1.852     albertel 13796: 	&load_hosts_tab() if (!$loaded);
                   13797: 
1.838     albertel 13798: 	my ($lonid) = @_;
                   13799: 	return $hostname{$lonid};
                   13800:     }
1.845     albertel 13801: 
1.838     albertel 13802:     sub all_hostnames {
1.852     albertel 13803: 	&load_hosts_tab() if (!$loaded);
                   13804: 
1.838     albertel 13805: 	return %hostname;
                   13806:     }
1.845     albertel 13807: 
1.888     albertel 13808:     sub all_names {
1.1172.2.70  raeburn  13809:         my ($ignore_cache,$nocache) = @_;
                   13810: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13811: 
                   13812: 	return %name_to_host;
                   13813:     }
                   13814: 
1.974     raeburn  13815:     sub all_host_domain {
                   13816:         &load_hosts_tab() if (!$loaded);
                   13817:         return %hostdom;
                   13818:     }
                   13819: 
1.845     albertel 13820:     sub is_library {
1.852     albertel 13821: 	&load_hosts_tab() if (!$loaded);
                   13822: 
1.845     albertel 13823: 	return exists($libserv{$_[0]});
                   13824:     }
                   13825: 
                   13826:     sub all_library {
1.852     albertel 13827: 	&load_hosts_tab() if (!$loaded);
                   13828: 
1.845     albertel 13829: 	return %libserv;
                   13830:     }
                   13831: 
1.1062    droeschl 13832:     sub unique_library {
                   13833: 	#2x reverse removes all hostnames that appear more than once
                   13834:         my %unique = reverse &all_library();
                   13835:         return reverse %unique;
                   13836:     }
                   13837: 
1.841     albertel 13838:     sub get_servers {
1.852     albertel 13839: 	&load_hosts_tab() if (!$loaded);
                   13840: 
1.841     albertel 13841: 	my ($domain,$type) = @_;
                   13842: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13843: 	                                          : %hostname;
                   13844: 	my %result;
1.842     albertel 13845: 	if (ref($domain) eq 'ARRAY') {
                   13846: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13847: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13848: 		    $result{$host} = $hostname;
                   13849: 		}
                   13850: 	    }
                   13851: 	} else {
                   13852: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13853: 		if ($hostdom{$host} eq $domain) {
                   13854: 		    $result{$host} = $hostname;
                   13855: 		}
1.841     albertel 13856: 	    }
                   13857: 	}
                   13858: 	return %result;
                   13859:     }
1.845     albertel 13860: 
1.1062    droeschl 13861:     sub get_unique_servers {
                   13862:         my %unique = reverse &get_servers(@_);
                   13863: 	return reverse %unique;
                   13864:     }
                   13865: 
1.844     albertel 13866:     sub host_domain {
1.852     albertel 13867: 	&load_hosts_tab() if (!$loaded);
                   13868: 
1.844     albertel 13869: 	my ($lonid) = @_;
                   13870: 	return $hostdom{$lonid};
                   13871:     }
                   13872: 
1.841     albertel 13873:     sub all_domains {
1.852     albertel 13874: 	&load_hosts_tab() if (!$loaded);
                   13875: 
1.841     albertel 13876: 	my %seen;
                   13877: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13878: 	return @uniq;
                   13879:     }
1.1074    raeburn  13880: 
                   13881:     sub internet_dom {
                   13882:         &load_hosts_tab() if (!$loaded);
                   13883: 
                   13884:         my ($lonid) = @_;
                   13885:         return $internetdom{$lonid};
                   13886:     }
1.1107    raeburn  13887: 
                   13888:     sub is_LC_dns {
                   13889:         &load_hosts_tab() if (!$loaded);
                   13890: 
                   13891:         my ($hostname) = @_;
                   13892:         return exists($LC_dns_serv{$hostname});
                   13893:     }
                   13894: 
1.1       albertel 13895: }
                   13896: 
1.847     albertel 13897: { 
                   13898:     my %iphost;
1.856     albertel 13899:     my %name_to_ip;
                   13900:     my %lonid_to_ip;
1.869     albertel 13901: 
1.847     albertel 13902:     sub get_hosts_from_ip {
                   13903: 	my ($ip) = @_;
                   13904: 	my %iphosts = &get_iphost();
                   13905: 	if (ref($iphosts{$ip})) {
                   13906: 	    return @{$iphosts{$ip}};
                   13907: 	}
                   13908: 	return;
1.839     albertel 13909:     }
1.864     albertel 13910:     
                   13911:     sub reset_hosts_ip_info {
                   13912: 	undef(%iphost);
                   13913: 	undef(%name_to_ip);
                   13914: 	undef(%lonid_to_ip);
                   13915:     }
1.856     albertel 13916: 
                   13917:     sub get_host_ip {
                   13918: 	my ($lonid) = @_;
                   13919: 	if (exists($lonid_to_ip{$lonid})) {
                   13920: 	    return $lonid_to_ip{$lonid};
                   13921: 	}
                   13922: 	my $name=&hostname($lonid);
                   13923:    	my $ip = gethostbyname($name);
                   13924: 	return if (!$ip || length($ip) ne 4);
                   13925: 	$ip=inet_ntoa($ip);
                   13926: 	$name_to_ip{$name}   = $ip;
                   13927: 	$lonid_to_ip{$lonid} = $ip;
                   13928: 	return $ip;
                   13929:     }
1.847     albertel 13930:     
                   13931:     sub get_iphost {
1.1172.2.70  raeburn  13932: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13933: 
1.869     albertel 13934: 	if (!$ignore_cache) {
                   13935: 	    if (%iphost) {
                   13936: 		return %iphost;
                   13937: 	    }
                   13938: 	    my ($ip_info,$cached)=
                   13939: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13940: 	    if ($cached) {
                   13941: 		%iphost      = %{$ip_info->[0]};
                   13942: 		%name_to_ip  = %{$ip_info->[1]};
                   13943: 		%lonid_to_ip = %{$ip_info->[2]};
                   13944: 		return %iphost;
                   13945: 	    }
                   13946: 	}
1.894     albertel 13947: 
                   13948: 	# get yesterday's info for fallback
                   13949: 	my %old_name_to_ip;
                   13950: 	my ($ip_info,$cached)=
                   13951: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13952: 	if ($cached) {
                   13953: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13954: 	}
                   13955: 
1.1172.2.70  raeburn  13956: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13957: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13958: 	    my $ip;
                   13959: 	    if (!exists($name_to_ip{$name})) {
                   13960: 		$ip = gethostbyname($name);
                   13961: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13962: 		    if (defined($old_name_to_ip{$name})) {
                   13963: 			$ip = $old_name_to_ip{$name};
                   13964: 			&logthis("Can't find $name defaulting to old $ip");
                   13965: 		    } else {
                   13966: 			&logthis("Name $name no IP found");
                   13967: 			next;
                   13968: 		    }
                   13969: 		} else {
                   13970: 		    $ip=inet_ntoa($ip);
1.847     albertel 13971: 		}
                   13972: 		$name_to_ip{$name} = $ip;
                   13973: 	    } else {
                   13974: 		$ip = $name_to_ip{$name};
1.653     albertel 13975: 	    }
1.888     albertel 13976: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13977: 		$lonid_to_ip{$id} = $ip;
                   13978: 	    }
                   13979: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13980: 	}
1.1172.2.70  raeburn  13981:         unless ($nocache) {
                   13982: 	    &do_cache_new('iphost','iphost',
                   13983: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13984: 		          48*60*60);
                   13985:         }
1.869     albertel 13986: 
1.847     albertel 13987: 	return %iphost;
1.598     albertel 13988:     }
                   13989: 
1.992     raeburn  13990:     #
                   13991:     #  Given a DNS returns the loncapa host name for that DNS 
                   13992:     # 
                   13993:     sub host_from_dns {
                   13994:         my ($dns) = @_;
                   13995:         my @hosts;
                   13996:         my $ip;
                   13997: 
1.993     raeburn  13998:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13999:             $ip = $name_to_ip{$dns};
                   14000:         }
                   14001:         if (!$ip) {
                   14002:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14003:             if (length($ip) == 4) { 
                   14004: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14005:             }
                   14006:         }
                   14007:         if ($ip) {
                   14008: 	    @hosts = get_hosts_from_ip($ip);
                   14009: 	    return $hosts[0];
                   14010:         }
                   14011:         return undef;
1.986     foxr     14012:     }
1.992     raeburn  14013: 
1.1074    raeburn  14014:     sub get_internet_names {
                   14015:         my ($lonid) = @_;
                   14016:         return if ($lonid eq '');
                   14017:         my ($idnref,$cached)=
                   14018:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14019:         if ($cached) {
                   14020:             return $idnref;
                   14021:         }
                   14022:         my $ip = &get_host_ip($lonid);
                   14023:         my @hosts = &get_hosts_from_ip($ip);
                   14024:         my %iphost = &get_iphost();
                   14025:         my (@idns,%seen);
                   14026:         foreach my $id (@hosts) {
                   14027:             my $dom = &host_domain($id);
                   14028:             my $prim_id = &domain($dom,'primary');
                   14029:             my $prim_ip = &get_host_ip($prim_id);
                   14030:             next if ($seen{$prim_ip});
                   14031:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14032:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14033:                     my $intdom = &internet_dom($id);
                   14034:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14035:                         push(@idns,$intdom);
                   14036:                     }
                   14037:                 }
                   14038:             }
                   14039:             $seen{$prim_ip} = 1;
                   14040:         }
1.1172.2.23  raeburn  14041:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14042:     }
                   14043: 
1.986     foxr     14044: }
                   14045: 
1.1079    raeburn  14046: sub all_loncaparevs {
1.1172.2.39  raeburn  14047:     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  14048: }
                   14049: 
1.1172.2.27  raeburn  14050: # ------------------------------------------------------- Read loncaparev table
                   14051: {
                   14052:     sub load_loncaparevs {
                   14053:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14054:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14055:                 while (my $configline=<$config>) {
                   14056:                     chomp($configline);
                   14057:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14058:                     $loncaparevs{$hostid}=$loncaparev;
                   14059:                 }
                   14060:                 close($config);
                   14061:             }
                   14062:         }
                   14063:     }
                   14064: }
                   14065: 
                   14066: # ----------------------------------------------------- Read serverhostID table
                   14067: {
                   14068:     sub load_serverhomeIDs {
                   14069:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14070:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14071:                 while (my $configline=<$config>) {
                   14072:                     chomp($configline);
                   14073:                     my ($name,$id)=split(/:/,$configline);
                   14074:                     $serverhomeIDs{$name}=$id;
                   14075:                 }
                   14076:                 close($config);
                   14077:             }
                   14078:         }
                   14079:     }
                   14080: }
                   14081: 
                   14082: 
1.862     albertel 14083: BEGIN {
                   14084: 
                   14085: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14086:     unless ($readit) {
                   14087: {
                   14088:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14089:     %perlvar = (%perlvar,%{$configvars});
                   14090: }
                   14091: 
                   14092: 
1.1       albertel 14093: # ------------------------------------------------------ Read spare server file
                   14094: {
1.1172.2.96  raeburn  14095:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14096: 
                   14097:     while (my $configline=<$config>) {
                   14098:        chomp($configline);
1.284     matthew  14099:        if ($configline) {
1.784     albertel 14100: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14101: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14102: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14103:        }
                   14104:     }
1.448     albertel 14105:     close($config);
1.1       albertel 14106: }
1.11      www      14107: # ------------------------------------------------------------ Read permissions
                   14108: {
1.1172.2.96  raeburn  14109:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14110: 
                   14111:     while (my $configline=<$config>) {
1.448     albertel 14112: 	chomp($configline);
                   14113: 	if ($configline) {
                   14114: 	    my ($role,$perm)=split(/ /,$configline);
                   14115: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14116: 	}
1.11      www      14117:     }
1.448     albertel 14118:     close($config);
1.11      www      14119: }
                   14120: 
                   14121: # -------------------------------------------- Read plain texts for permissions
                   14122: {
1.1172.2.96  raeburn  14123:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14124: 
                   14125:     while (my $configline=<$config>) {
1.448     albertel 14126: 	chomp($configline);
                   14127: 	if ($configline) {
1.742     raeburn  14128: 	    my ($short,@plain)=split(/:/,$configline);
                   14129:             %{$prp{$short}} = ();
                   14130: 	    if (@plain > 0) {
                   14131:                 $prp{$short}{'std'} = $plain[0];
                   14132:                 for (my $i=1; $i<@plain; $i++) {
                   14133:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14134:                 }
                   14135:             }
1.448     albertel 14136: 	}
1.135     www      14137:     }
1.448     albertel 14138:     close($config);
1.135     www      14139: }
                   14140: 
                   14141: # ---------------------------------------------------------- Read package table
                   14142: {
1.1172.2.96  raeburn  14143:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14144: 
                   14145:     while (my $configline=<$config>) {
1.483     albertel 14146: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14147: 	chomp($configline);
                   14148: 	my ($short,$plain)=split(/:/,$configline);
                   14149: 	my ($pack,$name)=split(/\&/,$short);
                   14150: 	if ($plain ne '') {
                   14151: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14152: 	    $packagetab{$short}=$plain; 
                   14153: 	}
1.11      www      14154:     }
1.448     albertel 14155:     close($config);
1.329     matthew  14156: }
                   14157: 
1.1172.2.27  raeburn  14158: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14159: 
1.1172.2.27  raeburn  14160: &load_loncaparevs();
                   14161: 
                   14162: # ------------------------------------------------------- Read serverhostID table
                   14163: 
                   14164: &load_serverhomeIDs();
1.1074    raeburn  14165: 
1.1172.2.27  raeburn  14166: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14167: {
                   14168:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14169:     if (-e $file) {
                   14170:         my $parser = HTML::LCParser->new($file);
                   14171:         while (my $token = $parser->get_token()) {
                   14172:             if ($token->[0] eq 'S') {
                   14173:                 my $item = $token->[1];
                   14174:                 my $name = $token->[2]{'name'};
                   14175:                 my $value = $token->[2]{'value'};
                   14176:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14177:                     my $release = $parser->get_text();
                   14178:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14179:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14180:                 }
                   14181:             }
                   14182:         }
                   14183:     }
1.1073    raeburn  14184: }
                   14185: 
1.1138    raeburn  14186: # ---------------------------------------------------------- Read managers table
                   14187: {
                   14188:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14189:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14190:             while (my $configline=<$config>) {
                   14191:                 chomp($configline);
                   14192:                 next if ($configline =~ /^\#/);
                   14193:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14194:                     $managerstab{$configline} = 1;
                   14195:                 }
                   14196:             }
                   14197:             close($config);
                   14198:         }
                   14199:     }
                   14200: }
                   14201: 
1.329     matthew  14202: # ------------- set up temporary directory
                   14203: {
1.1117    foxr     14204:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14205: 
1.11      www      14206: }
                   14207: 
1.1172.2.104  raeburn  14208: # ------------- set default texengine (domain default overrides this)
                   14209: {
                   14210:     $deftex = LONCAPA::texengine();
                   14211: }
                   14212: 
1.1172.2.114  raeburn  14213: # ------------- set default minimum length for passwords for internal auth users
                   14214: {
                   14215:     $passwdmin = LONCAPA::passwd_min();
                   14216: }
                   14217: 
1.794     albertel 14218: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14219: 				'compress_threshold'=> 20_000,
                   14220:  			        });
1.185     www      14221: 
1.281     www      14222: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14223: $dumpcount=0;
1.958     www      14224: $locknum=0;
1.22      www      14225: 
1.163     harris41 14226: &logtouch();
1.672     albertel 14227: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14228: $readit=1;
1.564     albertel 14229:     {
                   14230: 	use integer;
                   14231: 	my $test=(2**32)+1;
1.568     albertel 14232: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14233: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14234:     }
1.195     www      14235: }
1.1       albertel 14236: }
1.179     www      14237: 
1.1       albertel 14238: 1;
1.191     harris41 14239: __END__
                   14240: 
1.243     albertel 14241: =pod
                   14242: 
1.191     harris41 14243: =head1 NAME
                   14244: 
1.243     albertel 14245: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14246: 
                   14247: =head1 SYNOPSIS
                   14248: 
1.243     albertel 14249: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14250: 
                   14251:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14252: 
1.243     albertel 14253: Common parameters:
                   14254: 
                   14255: =over 4
                   14256: 
                   14257: =item *
                   14258: 
                   14259: $uname : an internal username (if $cname expecting a course Id specifically)
                   14260: 
                   14261: =item *
                   14262: 
                   14263: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14264: 
                   14265: =item *
                   14266: 
                   14267: $symb : a resource instance identifier
                   14268: 
                   14269: =item *
                   14270: 
                   14271: $namespace : the name of a .db file that contains the data needed or
                   14272: being set.
                   14273: 
                   14274: =back
                   14275: 
1.394     bowersj2 14276: =head1 OVERVIEW
1.191     harris41 14277: 
1.394     bowersj2 14278: lonnet provides subroutines which interact with the
                   14279: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14280: about classes, users, and resources.
1.243     albertel 14281: 
                   14282: For many of these objects you can also use this to store data about
                   14283: them or modify them in various ways.
1.191     harris41 14284: 
1.394     bowersj2 14285: =head2 Symbs
1.191     harris41 14286: 
1.394     bowersj2 14287: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14288: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14289: map, the resource number of the resource in the map, and the URL of
                   14290: the resource itself. The latter is somewhat redundant, but might help
                   14291: if maps change.
                   14292: 
                   14293: An example is
                   14294: 
                   14295:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14296: 
                   14297: The respective map entry is
                   14298: 
                   14299:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14300:   title="Problem 2">
                   14301:  </resource>
                   14302: 
                   14303: Symbs are used by the random number generator, as well as to store and
                   14304: restore data specific to a certain instance of for example a problem.
                   14305: 
                   14306: =head2 Storing And Retrieving Data
                   14307: 
                   14308: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14309: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14310: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14311: is is the non-critical message twin of cstore. These functions are for
                   14312: handlers to store a perl hash to a user's permanent data space in an
                   14313: easy manner, and to retrieve it again on another call. It is expected
                   14314: that a handler would use this once at the beginning to retrieve data,
                   14315: and then again once at the end to send only the new data back.
                   14316: 
                   14317: The data is stored in the user's data directory on the user's
                   14318: homeserver under the ID of the course.
                   14319: 
                   14320: The hash that is returned by restore will have all of the previous
                   14321: value for all of the elements of the hash.
                   14322: 
                   14323: Example:
                   14324: 
                   14325:  #creating a hash
                   14326:  my %hash;
                   14327:  $hash{'foo'}='bar';
                   14328: 
                   14329:  #storing it
                   14330:  &Apache::lonnet::cstore(\%hash);
                   14331: 
                   14332:  #changing a value
                   14333:  $hash{'foo'}='notbar';
                   14334: 
                   14335:  #adding a new value
                   14336:  $hash{'bar'}='foo';
                   14337:  &Apache::lonnet::cstore(\%hash);
                   14338: 
                   14339:  #retrieving the hash
                   14340:  my %history=&Apache::lonnet::restore();
                   14341: 
                   14342:  #print the hash
                   14343:  foreach my $key (sort(keys(%history))) {
                   14344:    print("\%history{$key} = $history{$key}");
                   14345:  }
                   14346: 
                   14347: Will print out:
1.191     harris41 14348: 
1.394     bowersj2 14349:  %history{1:foo} = bar
                   14350:  %history{1:keys} = foo:timestamp
                   14351:  %history{1:timestamp} = 990455579
                   14352:  %history{2:bar} = foo
                   14353:  %history{2:foo} = notbar
                   14354:  %history{2:keys} = foo:bar:timestamp
                   14355:  %history{2:timestamp} = 990455580
                   14356:  %history{bar} = foo
                   14357:  %history{foo} = notbar
                   14358:  %history{timestamp} = 990455580
                   14359:  %history{version} = 2
                   14360: 
                   14361: Note that the special hash entries C<keys>, C<version> and
                   14362: C<timestamp> were added to the hash. C<version> will be equal to the
                   14363: total number of versions of the data that have been stored. The
                   14364: C<timestamp> attribute will be the UNIX time the hash was
                   14365: stored. C<keys> is available in every historical section to list which
                   14366: keys were added or changed at a specific historical revision of a
                   14367: hash.
                   14368: 
                   14369: B<Warning>: do not store the hash that restore returns directly. This
                   14370: will cause a mess since it will restore the historical keys as if the
                   14371: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14372: 
1.394     bowersj2 14373: Calling convention:
1.191     harris41 14374: 
1.1172.2.27  raeburn  14375:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14376:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14377: 
1.394     bowersj2 14378: For more detailed information, see lonnet specific documentation.
1.191     harris41 14379: 
1.394     bowersj2 14380: =head1 RETURN MESSAGES
1.191     harris41 14381: 
1.394     bowersj2 14382: =over 4
1.191     harris41 14383: 
1.394     bowersj2 14384: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14385: 
1.394     bowersj2 14386: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14387: when the connection is brought back up
1.191     harris41 14388: 
1.394     bowersj2 14389: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14390: for later delivery
1.191     harris41 14391: 
1.967     bisitz   14392: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14393: 
1.394     bowersj2 14394: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14395: that was requested
1.191     harris41 14396: 
1.243     albertel 14397: =back
1.191     harris41 14398: 
1.243     albertel 14399: =head1 PUBLIC SUBROUTINES
1.191     harris41 14400: 
1.243     albertel 14401: =head2 Session Environment Functions
1.191     harris41 14402: 
1.243     albertel 14403: =over 4
1.191     harris41 14404: 
1.394     bowersj2 14405: =item * 
                   14406: X<appenv()>
1.949     raeburn  14407: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14408: the user envirnoment file, and will be restored for each access this
1.620     albertel 14409: user makes during this session, also modifies the %env for the current
1.949     raeburn  14410: process. Optional rolesarrayref - if defined contains a reference to an array
                   14411: of roles which are exempt from the restriction on modifying user.role entries 
                   14412: in the user's environment.db and in %env.    
1.191     harris41 14413: 
                   14414: =item *
1.394     bowersj2 14415: X<delenv()>
1.987     raeburn  14416: B<delenv($delthis,$regexp)>: removes all items from the session
                   14417: environment file that begin with $delthis. If the 
                   14418: optional second arg - $regexp - is true, $delthis is treated as a 
                   14419: regular expression, otherwise \Q$delthis\E is used. 
                   14420: The values are also deleted from the current processes %env.
1.191     harris41 14421: 
1.795     albertel 14422: =item * get_env_multiple($name) 
                   14423: 
                   14424: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14425: values may be defined and end up as an array ref.
                   14426: 
                   14427: returns an array of values
                   14428: 
1.243     albertel 14429: =back
                   14430: 
                   14431: =head2 User Information
1.191     harris41 14432: 
1.243     albertel 14433: =over 4
1.191     harris41 14434: 
                   14435: =item *
1.394     bowersj2 14436: X<queryauthenticate()>
                   14437: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14438: authentication scheme
                   14439: 
                   14440: =item *
1.394     bowersj2 14441: X<authenticate()>
1.1073    raeburn  14442: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14443: authenticate user from domain's lib servers (first use the current
                   14444: one). C<$upass> should be the users password.
1.1073    raeburn  14445: $checkdefauth is optional (value is 1 if a check should be made to
                   14446:    authenticate user using default authentication method, and allow
                   14447:    account creation if username does not have account in the domain).
                   14448: $clientcancheckhost is optional (value is 1 if checking whether the
                   14449:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14450: 
                   14451: =item *
1.394     bowersj2 14452: X<homeserver()>
                   14453: B<homeserver($uname,$udom)>: find the server which has
                   14454: the user's directory and files (there must be only one), this caches
                   14455: the answer, and also caches if there is a borken connection.
1.191     harris41 14456: 
                   14457: =item *
1.394     bowersj2 14458: X<idget()>
                   14459: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14460: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14461: username, and only 1 username per ID in a specific domain) (returns
                   14462: hash: id=>name,id=>name)
1.191     harris41 14463: 
                   14464: =item *
1.394     bowersj2 14465: X<idrget()>
                   14466: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14467: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14468: 
                   14469: =item *
1.394     bowersj2 14470: X<idput()>
                   14471: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14472: 
                   14473: =item *
1.394     bowersj2 14474: X<rolesinit()>
1.1169    droeschl 14475: B<rolesinit($udom,$username)>: get user privileges.
                   14476: returns user role, first access and timer interval hashes
1.243     albertel 14477: 
                   14478: =item *
1.1171    droeschl 14479: X<privileged()>
                   14480: B<privileged($username,$domain)>: returns a true if user has a
                   14481: privileged and active role (i.e. su or dc), false otherwise.
                   14482: 
                   14483: =item *
1.551     albertel 14484: X<getsection()>
                   14485: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14486: course $cname, return section name/number or '' for "not in course"
                   14487: and '-1' for "no section"
                   14488: 
                   14489: =item *
1.394     bowersj2 14490: X<userenvironment()>
                   14491: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14492: passed in @what from the requested user's environment, returns a hash
                   14493: 
1.858     raeburn  14494: =item * 
                   14495: X<userlog_query()>
1.859     albertel 14496: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14497: activity.log file. %filters defines filters applied when parsing the
                   14498: log file. These can be start or end timestamps, or the type of action
                   14499: - log to look for Login or Logout events, check for Checkin or
                   14500: Checkout, role for role selection. The response is in the form
                   14501: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14502: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14503: 
1.243     albertel 14504: =back
                   14505: 
                   14506: =head2 User Roles
                   14507: 
                   14508: =over 4
                   14509: 
                   14510: =item *
                   14511: 
1.1172.2.65  raeburn  14512: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14513: returns codes for allowed actions.
                   14514: 
                   14515: The first argument is required, all others are optional.
                   14516: 
                   14517: $priv is the privilege being checked.
                   14518: $uri contains additional information about what is being checked for access (e.g.,
                   14519: URL, course ID etc.).
                   14520: $symb is the unique resource instance identifier in a course; if needed,
                   14521: but not provided, it will be retrieved via a call to &symbread().
                   14522: $role is the role for which a priv is being checked (only used if priv is evb).
                   14523: $clientip is the user's IP address (only used when checking for access to portfolio
                   14524: files).
                   14525: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14526: prevents recursive calls to &allowed.
                   14527: 
1.243     albertel 14528:  F: full access
                   14529:  U,I,K: authentication modes (cxx only)
                   14530:  '': forbidden
                   14531:  1: user needs to choose course
                   14532:  2: browse allowed
1.766     albertel 14533:  A: passphrase authentication needed
1.1172.2.65  raeburn  14534:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14535: 
                   14536: =item *
                   14537: 
1.1172.2.13  raeburn  14538: constructaccess($url,$setpriv) : check for access to construction space URL
                   14539: 
                   14540: See if the owner domain and name in the URL match those in the
                   14541: expected environment.  If so, return three element list
                   14542: ($ownername,$ownerdomain,$ownerhome).
                   14543: 
                   14544: Otherwise return the null string.
                   14545: 
                   14546: If second argument 'setpriv' is true, it assigns the privileges,
                   14547: and returns the same three element list, unless the owner has
                   14548: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14549: in which case the null string is returned.
                   14550: 
                   14551: =item *
                   14552: 
1.1172.2.84  raeburn  14553: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14554: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14555: for system, domain, and course level. $uname and $udom are optional (current
                   14556: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14557: 
                   14558: =item *
                   14559: 
1.988     raeburn  14560: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14561: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14562: $type is Course (default) or Community.
1.988     raeburn  14563: If $forcedefault evaluates to true, text returned will be default 
                   14564: text for $type. Otherwise, if this is a course, the text returned 
                   14565: will be a custom name for the role (if defined in the course's 
                   14566: environment).  If no custom name is defined the default is returned.
                   14567:    
1.832     raeburn  14568: =item *
                   14569: 
1.1172.2.23  raeburn  14570: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14571: All arguments are optional. Returns a hash of a roles, either for
                   14572: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14573: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14574: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14575: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14576: For each key, value is set to colon-separated start and end times for
                   14577: the role.  If no username and domain are specified, will default to
1.934     raeburn  14578: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14579: of role statuses (active, future or previous), roles 
                   14580: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14581: to restrict the list of roles reported. If no array ref is 
                   14582: provided for types, will default to return only active roles.
1.834     albertel 14583: 
1.1172.2.13  raeburn  14584: =item *
                   14585: 
                   14586: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14587: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14588: 
                   14589: Additional optional arguments are: $type (if role checking is to be restricted
                   14590: to certain user status types -- previous (expired roles), active (currently
                   14591: available roles) or future (roles available in the future), and
                   14592: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14593: have active Domain Coordinator role in course's domain or in additional
                   14594: domains (specified in 'Domains to check for privileged users' in course
                   14595: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14596: 
                   14597: =item *
                   14598: 
                   14599: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14600: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14601: $possdomains and $possroles are optional array refs -- to domains to check and
                   14602: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14603: users' roles.db to check for a dc or su role in any domain. This can be
                   14604: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14605: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14606: this then allows &privileged_by_domain() to be used, which caches the identity
                   14607: of privileged users, eliminating the need for repeated calls to &dump().
                   14608: 
                   14609: =item *
                   14610: 
                   14611: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14612: where the outer hash keys are domains specified in the $possdomains array ref,
                   14613: next inner hash keys are privileged roles specified in the $roles array ref,
                   14614: and the innermost hash contains key = value pairs for username:domain = end:start
                   14615: for active or future "privileged" users with that role in that domain. To avoid
                   14616: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14617: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14618: 
1.243     albertel 14619: =back
                   14620: 
                   14621: =head2 User Modification
                   14622: 
                   14623: =over 4
                   14624: 
                   14625: =item *
                   14626: 
1.957     raeburn  14627: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14628: user for the level given by URL.  Optional start and end dates (leave empty
                   14629: string or zero for "no date")
1.191     harris41 14630: 
                   14631: =item *
                   14632: 
1.243     albertel 14633: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14634: change a users, password, possible return values are: ok,
                   14635: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14636: refused
1.191     harris41 14637: 
                   14638: =item *
                   14639: 
1.243     albertel 14640: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14641: 
                   14642: =item *
                   14643: 
1.1058    raeburn  14644: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14645:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14646: 
                   14647: will update user information (firstname,middlename,lastname,generation,
                   14648: permanentemail), and if forceid is true, student/employee ID also.
                   14649: A user's institutional affiliation(s) can also be updated.
                   14650: User information fields will not be overwritten with empty entries 
                   14651: unless the field is included in the $candelete array reference.
                   14652: This array is included when a single user is modified via "Manage Users",
                   14653: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14654: 
                   14655: =item *
                   14656: 
1.286     matthew  14657: modifystudent
                   14658: 
1.957     raeburn  14659: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14660: The course id is resolved based on the current user's environment.  
                   14661: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14662: associated with a course.
                   14663: 
1.297     matthew  14664: This call is essentially a wrapper for lonnet::modifyuser and
                   14665: lonnet::modify_student_enrollment
1.286     matthew  14666: 
                   14667: Inputs: 
                   14668: 
                   14669: =over 4
                   14670: 
1.957     raeburn  14671: =item B<$udom> Student's loncapa domain
1.286     matthew  14672: 
1.957     raeburn  14673: =item B<$uname> Student's loncapa login name
1.286     matthew  14674: 
1.964     bisitz   14675: =item B<$uid> Student/Employee ID
1.286     matthew  14676: 
1.957     raeburn  14677: =item B<$umode> Student's authentication mode
1.286     matthew  14678: 
1.957     raeburn  14679: =item B<$upass> Student's password
1.286     matthew  14680: 
1.957     raeburn  14681: =item B<$first> Student's first name
1.286     matthew  14682: 
1.957     raeburn  14683: =item B<$middle> Student's middle name
1.286     matthew  14684: 
1.957     raeburn  14685: =item B<$last> Student's last name
1.286     matthew  14686: 
1.957     raeburn  14687: =item B<$gene> Student's generation
1.286     matthew  14688: 
1.957     raeburn  14689: =item B<$usec> Student's section in course
1.286     matthew  14690: 
                   14691: =item B<$end> Unix time of the roles expiration
                   14692: 
                   14693: =item B<$start> Unix time of the roles start date
                   14694: 
                   14695: =item B<$forceid> If defined, allow $uid to be changed
                   14696: 
                   14697: =item B<$desiredhome> server to use as home server for student
                   14698: 
1.957     raeburn  14699: =item B<$email> Student's permanent e-mail address
                   14700: 
                   14701: =item B<$type> Type of enrollment (auto or manual)
                   14702: 
1.963     raeburn  14703: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14704: 
                   14705: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14706: 
1.963     raeburn  14707: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14708: 
1.963     raeburn  14709: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14710: 
1.1172.2.19  raeburn  14711: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14712: 
                   14713: =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  14714: 
1.286     matthew  14715: =back
1.297     matthew  14716: 
                   14717: =item *
                   14718: 
                   14719: modify_student_enrollment
                   14720: 
1.1172.2.31  raeburn  14721: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14722: 'role.request.course' must be defined for this function to proceed.
                   14723: 
                   14724: Inputs:
                   14725: 
                   14726: =over 4
                   14727: 
1.1172.2.31  raeburn  14728: =item $udom, student's domain
1.297     matthew  14729: 
1.1172.2.31  raeburn  14730: =item $uname, student's name
1.297     matthew  14731: 
1.1172.2.31  raeburn  14732: =item $uid, student's user id
1.297     matthew  14733: 
1.1172.2.31  raeburn  14734: =item $first, student's first name
1.297     matthew  14735: 
                   14736: =item $middle
                   14737: 
                   14738: =item $last
                   14739: 
                   14740: =item $gene
                   14741: 
                   14742: =item $usec
                   14743: 
                   14744: =item $end
                   14745: 
                   14746: =item $start
                   14747: 
1.957     raeburn  14748: =item $type
                   14749: 
                   14750: =item $locktype
                   14751: 
                   14752: =item $cid
                   14753: 
                   14754: =item $selfenroll
                   14755: 
                   14756: =item $context
                   14757: 
1.1172.2.19  raeburn  14758: =item $credits, number of credits student will earn from this class
                   14759: 
1.1172.2.76  raeburn  14760: =item $instsec, institutional course section code for student
                   14761: 
1.297     matthew  14762: =back
                   14763: 
1.191     harris41 14764: 
                   14765: =item *
                   14766: 
1.243     albertel 14767: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14768: custom role; give a custom role to a user for the level given by URL.  Specify
                   14769: name and domain of role author, and role name
1.191     harris41 14770: 
                   14771: =item *
                   14772: 
1.243     albertel 14773: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14774: 
                   14775: =item *
                   14776: 
1.243     albertel 14777: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14778: 
                   14779: =back
                   14780: 
                   14781: =head2 Course Infomation
                   14782: 
                   14783: =over 4
1.191     harris41 14784: 
                   14785: =item *
                   14786: 
1.1118    foxr     14787: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14788: specified course id, including all environment settings for the
                   14789: course, the description of the course will be in the hash under the
                   14790: key 'description'
1.191     harris41 14791: 
1.1118    foxr     14792: $options is an optional parameter that if supplied is a hash reference that controls
                   14793: what how this function works.  It has the following key/values:
                   14794: 
                   14795: =over 4
                   14796: 
                   14797: =item freshen_cache
                   14798: 
                   14799: If defined, and the environment cache for the course is valid, it is 
                   14800: returned in the returned hash.
                   14801: 
                   14802: =item one_time
                   14803: 
                   14804: If defined, the last cache time is set to _now_
                   14805: 
                   14806: =item user
                   14807: 
                   14808: If defined, the supplied username is used instead of the current user.
                   14809: 
                   14810: 
                   14811: =back
                   14812: 
1.191     harris41 14813: =item *
                   14814: 
1.624     albertel 14815: resdata($name,$domain,$type,@which) : request for current parameter
                   14816: setting for a specific $type, where $type is either 'course' or 'user',
                   14817: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14818: answers for 10 minutes.
1.243     albertel 14819: 
1.877     foxr     14820: =item *
                   14821: 
                   14822: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14823: data base, returning a hash that is keyed by the resource name and has
                   14824: values that are the resource value.  I believe that the timestamps and
                   14825: versions are also returned.
                   14826: 
1.1172.2.31  raeburn  14827: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14828: supplemental content area. This routine caches the number of files for
                   14829: 10 minutes.
                   14830: 
1.243     albertel 14831: =back
                   14832: 
                   14833: =head2 Course Modification
                   14834: 
                   14835: =over 4
1.191     harris41 14836: 
                   14837: =item *
                   14838: 
1.243     albertel 14839: writecoursepref($courseid,%prefs) : write preferences (environment
                   14840: database) for a course
1.191     harris41 14841: 
                   14842: =item *
                   14843: 
1.1011    raeburn  14844: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14845: 
                   14846: =item *
                   14847: 
1.1038    raeburn  14848: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14849: 
1.1167    droeschl 14850: =item *
                   14851: 
                   14852: is_course($courseid), is_course($cdom, $cnum)
                   14853: 
                   14854: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14855: two component version $cdom, $cnum. It checks if the specified course exists.
                   14856: 
                   14857: Returns:
                   14858:     undef if the course doesn't exist, otherwise
                   14859:     in scalar context the combined courseid.
                   14860:     in list context the two components of the course identifier, domain and 
                   14861:     courseid.    
                   14862: 
1.243     albertel 14863: =back
                   14864: 
1.1172.2.109  raeburn  14865: =head2 Bubblesheet Configuration
                   14866: 
                   14867: =over 4
                   14868: 
                   14869: =item *
                   14870: 
                   14871: get_scantron_config($which)
                   14872: 
                   14873: $which - the name of the configuration to parse from the file.
                   14874: 
                   14875: Parses and returns the bubblesheet configuration line selected as a
                   14876: hash of configuration file fields.
                   14877: 
                   14878: 
                   14879: Returns:
                   14880:     If the named configuration is not in the file, an empty
                   14881:     hash is returned.
                   14882: 
                   14883:     a hash with the fields
                   14884:       name         - internal name for the this configuration setup
                   14885:       description  - text to display to operator that describes this config
                   14886:       CODElocation - if 0 or the string 'none'
                   14887:                           - no CODE exists for this config
                   14888:                      if -1 || the string 'letter'
                   14889:                           - a CODE exists for this config and is
                   14890:                             a string of letters
                   14891:                      Unsupported value (but planned for future support)
                   14892:                           if a positive integer
                   14893:                                - The CODE exists as the first n items from
                   14894:                                  the question section of the form
                   14895:                           if the string 'number'
                   14896:                                - The CODE exists for this config and is
                   14897:                                  a string of numbers
                   14898:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14899:                      the CODE starts
                   14900:       CODElength  - length of the CODE
                   14901:       IDstart     - column where the student/employee ID starts
                   14902:       IDlength    - length of the student/employee ID info
                   14903:       Qstart      - column where the information from the bubbled
                   14904:                     'questions' start
                   14905:       Qlength     - number of columns comprising a single bubble line from
                   14906:                     the sheet. (usually either 1 or 10)
                   14907:       Qon         - either a single character representing the character used
                   14908:                     to signal a bubble was chosen in the positional setup, or
                   14909:                     the string 'letter' if the letter of the chosen bubble is
                   14910:                     in the final, or 'number' if a number representing the
                   14911:                     chosen bubble is in the file (1->A 0->J)
                   14912:       Qoff        - the character used to represent that a bubble was
                   14913:                     left blank
                   14914:       PaperID     - if the scanning process generates a unique number for each
                   14915:                     sheet scanned the column that this ID number starts in
                   14916:       PaperIDlength - number of columns that comprise the unique ID number
                   14917:                       for the sheet of paper
                   14918:       FirstName   - column that the first name starts in
                   14919:       FirstNameLength - number of columns that the first name spans
                   14920:       LastName    - column that the last name starts in
                   14921:       LastNameLength - number of columns that the last name spans
                   14922:       BubblesPerRow - number of bubbles available in each row used to
                   14923:                       bubble an answer. (If not specified, 10 assumed).
                   14924: 
                   14925: 
                   14926: =item *
                   14927: 
                   14928: get_scantronformat_file($cdom)
                   14929: 
                   14930: $cdom - the course's domain (optional); if not supplied, uses
                   14931: domain for current $env{'request.course.id'}.
                   14932: 
                   14933: Returns an array containing lines from the scantron format file for
                   14934: the domain of the course.
                   14935: 
                   14936: If a url for a custom.tab file is listed in domain's configuration.db,
                   14937: lines are from this file.
                   14938: 
                   14939: Otherwise, if a default.tab has been published in RES space by the
                   14940: domainconfig user, lines are from this file.
                   14941: 
                   14942: Otherwise, fall back to getting lines from the legacy file on the
                   14943: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14944: 
                   14945: =back
                   14946: 
1.243     albertel 14947: =head2 Resource Subroutines
                   14948: 
                   14949: =over 4
1.191     harris41 14950: 
                   14951: =item *
                   14952: 
1.243     albertel 14953: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14954: 
                   14955: =item *
                   14956: 
1.243     albertel 14957: repcopy($filename) : subscribes to the requested file, and attempts to
                   14958: replicate from the owning library server, Might return
1.607     raeburn  14959: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14960: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14961: resource. Expects the local filesystem pathname
                   14962: (/home/httpd/html/res/....)
                   14963: 
                   14964: =back
                   14965: 
                   14966: =head2 Resource Information
                   14967: 
                   14968: =over 4
1.191     harris41 14969: 
                   14970: =item *
                   14971: 
1.1172.2.28  raeburn  14972: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14973: and returns the value of a variety of different possible values,
                   14974: $varname should be a request string, and the other parameters can be
                   14975: used to specify who and what one is asking about. Ordinarily, $cid 
                   14976: does not need to be specified, as it is retrived from 
                   14977: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14978: within lonuserstate::loadmap() when initializing a course, before
                   14979: $env{'request.course.id'} has been set, so it needs to be provided
                   14980: in that one case.
1.243     albertel 14981: 
                   14982: Possible values for $varname are environment.lastname (or other item
                   14983: from the envirnment hash), user.name (or someother aspect about the
                   14984: user), resource.0.maxtries (or some other part and parameter of a
                   14985: resource)
1.204     albertel 14986: 
                   14987: =item *
                   14988: 
1.243     albertel 14989: directcondval($number) : get current value of a condition; reads from a state
                   14990: string
1.204     albertel 14991: 
                   14992: =item *
                   14993: 
1.243     albertel 14994: condval($condidx) : value of condition index based on state
1.204     albertel 14995: 
                   14996: =item *
                   14997: 
1.243     albertel 14998: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14999: resource's metadata, $what should be either a specific key, or either
                   15000: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15001: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15002: 
                   15003: this function automatically caches all requests
1.191     harris41 15004: 
                   15005: =item *
                   15006: 
1.243     albertel 15007: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15008: network of library servers; returns file handle of where SQL and regex results
                   15009: will be stored for query
1.191     harris41 15010: 
                   15011: =item *
                   15012: 
1.1172.2.66  raeburn  15013: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15014: return symbolic list entry (all arguments optional).
                   15015: 
                   15016: Args: filename is the filename (including path) for the file for which a symb
                   15017: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15018: to check access status if more than one resource was found in the bighash
                   15019: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15020: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15021: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15022: cause possible symbs to be checked to determine if they are subject to content
                   15023: blocking, if so they will not be included as possible symbs; possibles is a
                   15024: ref to a hash, which, as a side effect, will be populated with all possible
                   15025: symbs (content blocking not tested).
                   15026: 
1.243     albertel 15027: returns the data handle
1.191     harris41 15028: 
                   15029: =item *
                   15030: 
1.1172.2.17  raeburn  15031: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15032: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15033: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15034: on failure, user must be in a course, as it assumes the existence of
                   15035: the course initial hash, and uses $env('request.course.id'}.  The third
                   15036: arg is an optional reference to a scalar.  If this arg is passed in the
                   15037: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15038: encrypted; otherwise it will be null.
1.243     albertel 15039: 
1.191     harris41 15040: =item *
                   15041: 
1.243     albertel 15042: symbclean($symb) : removes versions numbers from a symb, returns the
                   15043: cleaned symb
1.191     harris41 15044: 
                   15045: =item *
                   15046: 
1.243     albertel 15047: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15048: course map, user must be in a course for it to work.
1.191     harris41 15049: 
                   15050: =item *
                   15051: 
1.243     albertel 15052: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15053: 
                   15054: =item *
                   15055: 
1.243     albertel 15056: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15057: a random seed, all arguments are optional, if they aren't sent it uses the
                   15058: environment to derive them. Note: if symb isn't sent and it can't get one
                   15059: from &symbread it will use the current time as its return value
1.191     harris41 15060: 
                   15061: =item *
                   15062: 
1.243     albertel 15063: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15064: unfakeable, receipt
1.191     harris41 15065: 
                   15066: =item *
                   15067: 
1.620     albertel 15068: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15069: 
                   15070: =item *
                   15071: 
1.243     albertel 15072: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15073: 
                   15074: =item *
                   15075: 
1.243     albertel 15076: 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 15077: 
                   15078: =item *
                   15079: 
1.243     albertel 15080: 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 15081: 
                   15082: =item *
                   15083: 
1.243     albertel 15084: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15085: 
                   15086: =item *
                   15087: 
1.243     albertel 15088: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15089: forcing spreadsheet to reevaluate the resource scores next time.
                   15090: 
1.1172.2.13  raeburn  15091: =item *
                   15092: 
                   15093: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15094: when viewing in course context.
                   15095: 
                   15096:  input: six args -- filename (decluttered), course number, course domain,
                   15097:                     url, symb (if registered) and group (if this is a
                   15098:                     group item -- e.g., bulletin board, group page etc.).
                   15099: 
                   15100:  output: array of five scalars --
                   15101:          $cfile -- url for file editing if editable on current server
                   15102:          $home -- homeserver of resource (i.e., for author if published,
                   15103:                                           or course if uploaded.).
                   15104:          $switchserver --  1 if server switch will be needed.
                   15105:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15106:          $forceview -- 1 if icon/link should be to go to view mode
                   15107: 
                   15108: =item *
                   15109: 
                   15110: is_course_upload($file,$cnum,$cdom)
                   15111: 
                   15112: Used in course context to determine if current file was uploaded to
                   15113: the course (i.e., would be found in /userfiles/docs on the course's
                   15114: homeserver.
                   15115: 
                   15116:   input: 3 args -- filename (decluttered), course number and course domain.
                   15117:   output: boolean -- 1 if file was uploaded.
                   15118: 
1.243     albertel 15119: =back
                   15120: 
                   15121: =head2 Storing/Retreiving Data
                   15122: 
                   15123: =over 4
1.191     harris41 15124: 
                   15125: =item *
                   15126: 
1.1172.2.64  raeburn  15127: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15128: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15129: the remaining args aren't required and if they aren't passed or are '' they will
                   15130: be derived from the env (with the exception of $laststore, which is an
                   15131: optional arg used when a user's submission is stored in grading).
                   15132: $laststore is $version=$timestamp, where $version is the most recent version
                   15133: number retrieved for the corresponding $symb in the $namespace db file, and
                   15134: $timestamp is the timestamp for that transaction (UNIX time).
                   15135: $laststore is currently only passed when cstore() is called by
                   15136: structuretags::finalize_storage().
1.191     harris41 15137: 
                   15138: =item *
                   15139: 
1.1172.2.64  raeburn  15140: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15141: but uses critical subroutine
1.191     harris41 15142: 
                   15143: =item *
                   15144: 
1.243     albertel 15145: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15146: all args are optional
1.191     harris41 15147: 
                   15148: =item *
                   15149: 
1.717     albertel 15150: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15151: dumps the complete (or key matching regexp) namespace into a hash
                   15152: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15153: normally &store()ed into
                   15154: 
                   15155: $range should be either an integer '100' (give me the first 100
                   15156:                                            matching records)
                   15157:               or be  two integers sperated by a - with no spaces
                   15158:                  '30-50' (give me the 30th through the 50th matching
                   15159:                           records)
                   15160: 
                   15161: 
                   15162: =item *
                   15163: 
1.1172.2.59  raeburn  15164: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15165: replaces a &store() version of data with a replacement set of data
                   15166: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15167: reference. If $tolog is true, the transaction is logged in the courselog
                   15168: with an action=PUTSTORE.
1.717     albertel 15169: 
                   15170: =item *
                   15171: 
1.243     albertel 15172: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15173: works very similar to store/cstore, but all data is stored in a
                   15174: temporary location and can be reset using tmpreset, $storehash should
                   15175: be a hash reference, returns nothing on success
1.191     harris41 15176: 
                   15177: =item *
                   15178: 
1.243     albertel 15179: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15180: similar to restore, but all data is stored in a temporary location and
                   15181: can be reset using tmpreset. Returns a hash of values on success,
                   15182: error string otherwise.
1.191     harris41 15183: 
                   15184: =item *
                   15185: 
1.243     albertel 15186: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15187: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15188: 
                   15189: =item *
                   15190: 
1.243     albertel 15191: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15192: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15193: 
                   15194: =item *
                   15195: 
1.243     albertel 15196: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15197: namesp ($udom and $uname are optional)
1.191     harris41 15198: 
                   15199: =item *
                   15200: 
1.702     albertel 15201: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15202: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15203: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15204: 
1.702     albertel 15205: $range should be either an integer '100' (give me the first 100
                   15206:                                            matching records)
                   15207:               or be  two integers sperated by a - with no spaces
                   15208:                  '30-50' (give me the 30th through the 50th matching
                   15209:                           records)
1.449     matthew  15210: =item *
                   15211: 
                   15212: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15213: $store can be a scalar, an array reference, or if the amount to be 
                   15214: incremented is > 1, a hash reference.
                   15215: 
                   15216: ($udom and $uname are optional)
1.191     harris41 15217: 
                   15218: =item *
                   15219: 
1.243     albertel 15220: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15221: ($udom and $uname are optional)
1.191     harris41 15222: 
                   15223: =item *
                   15224: 
1.243     albertel 15225: cput($namespace,$storehash,$udom,$uname) : critical put
                   15226: ($udom and $uname are optional)
1.191     harris41 15227: 
                   15228: =item *
                   15229: 
1.748     albertel 15230: newput($namespace,$storehash,$udom,$uname) :
                   15231: 
                   15232: Attempts to store the items in the $storehash, but only if they don't
                   15233: currently exist, if this succeeds you can be certain that you have 
                   15234: successfully created a new key value pair in the $namespace db.
                   15235: 
                   15236: 
                   15237: Args:
                   15238:  $namespace: name of database to store values to
                   15239:  $storehash: hashref to store to the db
                   15240:  $udom: (optional) domain of user containing the db
                   15241:  $uname: (optional) name of user caontaining the db
                   15242: 
                   15243: Returns:
                   15244:  'ok' -> succeeded in storing all keys of $storehash
                   15245:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15246:                         least <key> already existed in the db (other
                   15247:                         requested keys may also already exist)
1.967     bisitz   15248:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15249:  'con_lost' -> unable to contact request server
                   15250:  'refused' -> action was not allowed by remote machine
                   15251: 
                   15252: 
                   15253: =item *
                   15254: 
1.243     albertel 15255: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15256: reference filled in from namesp (encrypts the return communication)
                   15257: ($udom and $uname are optional)
1.191     harris41 15258: 
                   15259: =item *
                   15260: 
1.243     albertel 15261: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15262: critical subroutine
                   15263: 
1.806     raeburn  15264: =item *
                   15265: 
1.860     raeburn  15266: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15267: array reference filled in from namespace found in domain level on either
                   15268: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15269: 
                   15270: =item *
                   15271: 
1.860     raeburn  15272: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15273: domain level either on specified domain server ($uhome) or primary domain 
                   15274: server ($udom and $uhome are optional)
1.806     raeburn  15275: 
1.943     raeburn  15276: =item * 
                   15277: 
1.1172.2.35  raeburn  15278: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15279: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15280: the target domain.
                   15281: 
                   15282: May also include additional key => value pairs for the following groups:
                   15283: 
                   15284: =over
                   15285: 
                   15286: =item
                   15287: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15288: 
                   15289: =over
                   15290: 
                   15291: =item defaultquota, authorquota
                   15292: 
                   15293: =back
                   15294: 
                   15295: =item
                   15296: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15297: portfolio for users).
                   15298: 
                   15299: =over
                   15300: 
                   15301: =item
                   15302: aboutme, blog, webdav, portfolio
                   15303: 
                   15304: =back
                   15305: 
                   15306: =item
                   15307: requestcourses: ability to request courses, and how requests are processed.
                   15308: 
                   15309: =over
                   15310: 
                   15311: =item
1.1172.2.37  raeburn  15312: official, unofficial, community, textbook
1.1172.2.35  raeburn  15313: 
                   15314: =back
                   15315: 
                   15316: =item
                   15317: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15318: 
                   15319: =over
                   15320: 
                   15321: =item
1.1172.2.44  raeburn  15322: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15323: 
                   15324: =back
                   15325: 
                   15326: =item
                   15327: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15328: for course's uploaded content.
                   15329: 
                   15330: =over
                   15331: 
                   15332: =item
1.1172.2.68  raeburn  15333: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15334: communityquota, textbookquota
1.1172.2.35  raeburn  15335: 
                   15336: =back
                   15337: 
                   15338: =item
                   15339: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15340: on your servers.
                   15341: 
                   15342: =over
                   15343: 
                   15344: =item
                   15345: remotesessions, hostedsessions
                   15346: 
                   15347: =back
                   15348: 
                   15349: =back
                   15350: 
                   15351: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15352: utility to create a configuration.db file on a domain's primary library server
                   15353: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15354: -- corresponding values are authentication type (internal, krb4, krb5,
                   15355: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15356: will be available. Values are retrieved from cache (if current), unless the
                   15357: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15358: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15359: 
                   15360: Typical usage:
1.943     raeburn  15361: 
1.1172.2.35  raeburn  15362: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15363: 
1.243     albertel 15364: =back
                   15365: 
                   15366: =head2 Network Status Functions
                   15367: 
                   15368: =over 4
1.191     harris41 15369: 
                   15370: =item *
                   15371: 
1.1137    raeburn  15372: dirlist() : return directory list based on URI (first arg).
                   15373: 
                   15374: Inputs: 1 required, 5 optional.
                   15375: 
                   15376: =over
                   15377: 
                   15378: =item 
                   15379: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15380: 
                   15381: =item
                   15382: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15383: 
                   15384: =item
                   15385: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15386: 
                   15387: =item
                   15388: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15389: 
                   15390: =item
                   15391: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15392: 
                   15393: =item 
                   15394: $alternateRoot - path to prepend in place of path from $uri.
                   15395: 
                   15396: =back
                   15397: 
                   15398: Returns: Array of up to two items.
                   15399: 
                   15400: =over
                   15401: 
                   15402: a reference to an array of files/subdirectories
                   15403: 
                   15404: =over
                   15405: 
                   15406: Each element in the array of files/subdirectories is a & separated list of
                   15407: item name and the result of running stat on the item.  If dirlist was requested
                   15408: for a file instead of a directory, the item name will be ''. For a directory 
                   15409: listing, if the item is a metadata file, the element will end &N&M 
                   15410: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15411: default copyright set (1).  
                   15412: 
                   15413: =back
                   15414: 
                   15415: a scalar containing error condition (if encountered).
                   15416: 
                   15417: =over
                   15418: 
                   15419: =item 
                   15420: no_host (no homeserver identified for $username:$domain).
                   15421: 
                   15422: =item 
                   15423: no_such_host (server contacted for listing not identified as valid host).
                   15424: 
                   15425: =item 
                   15426: con_lost (connection to remote server failed).
                   15427: 
                   15428: =item 
                   15429: refused (invalid $username:$domain received on lond side).
                   15430: 
                   15431: =item 
                   15432: no_such_dir (directory at specified path on lond side does not exist). 
                   15433: 
                   15434: =item 
                   15435: empty (directory at specified path on lond side is empty).
                   15436: 
                   15437: =over
                   15438: 
                   15439: This is currently not encountered because the &ls3, &ls2, 
                   15440: &ls (_handler) routines on the lond side do not filter out
                   15441: . and .. from a directory listing. 
                   15442: 
                   15443: =back
                   15444: 
                   15445: =back
                   15446: 
                   15447: =back
1.191     harris41 15448: 
                   15449: =item *
                   15450: 
1.243     albertel 15451: spareserver() : find server with least workload from spare.tab
                   15452: 
1.986     foxr     15453: 
                   15454: =item *
                   15455: 
                   15456: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15457: if there is no corresponding loncapa host.
                   15458: 
1.243     albertel 15459: =back
                   15460: 
1.986     foxr     15461: 
1.243     albertel 15462: =head2 Apache Request
                   15463: 
                   15464: =over 4
1.191     harris41 15465: 
                   15466: =item *
                   15467: 
1.243     albertel 15468: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15469: localhost, posts hash
                   15470: 
                   15471: =back
                   15472: 
                   15473: =head2 Data to String to Data
                   15474: 
                   15475: =over 4
1.191     harris41 15476: 
                   15477: =item *
                   15478: 
1.243     albertel 15479: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15480: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15481: 
                   15482: =item *
                   15483: 
1.243     albertel 15484: hashref2str($hashref) : convert a hashref into a string complete with
                   15485: escaping and '=' and '&' separators, supports elements that are
                   15486: arrayrefs and hashrefs
1.191     harris41 15487: 
                   15488: =item *
                   15489: 
1.243     albertel 15490: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15491: with escaping and '&' separators, supports elements that are arrayrefs
                   15492: and hashrefs
1.191     harris41 15493: 
                   15494: =item *
                   15495: 
1.243     albertel 15496: str2hash($string) : convert string to hash using unescaping and
                   15497: splitting on '=' and '&', supports elements that are arrayrefs and
                   15498: hashrefs
1.191     harris41 15499: 
                   15500: =item *
                   15501: 
1.243     albertel 15502: str2array($string) : convert string to hash using unescaping and
                   15503: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15504: 
                   15505: =back
                   15506: 
                   15507: =head2 Logging Routines
                   15508: 
                   15509: 
                   15510: These routines allow one to make log messages in the lonnet.log and
                   15511: lonnet.perm logfiles.
1.191     harris41 15512: 
1.1119    foxr     15513: =over 4
                   15514: 
1.191     harris41 15515: =item *
                   15516: 
1.243     albertel 15517: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15518: 
                   15519: =item *
                   15520: 
1.243     albertel 15521: logthis() : append message to the normal lonnet.log file, it gets
                   15522: preiodically rolled over and deleted.
1.191     harris41 15523: 
                   15524: =item *
                   15525: 
1.243     albertel 15526: logperm() : append a permanent message to lonnet.perm.log, this log
                   15527: file never gets deleted by any automated portion of the system, only
                   15528: messages of critical importance should go in here.
                   15529: 
1.1119    foxr     15530: 
1.243     albertel 15531: =back
                   15532: 
                   15533: =head2 General File Helper Routines
                   15534: 
                   15535: =over 4
1.191     harris41 15536: 
                   15537: =item *
                   15538: 
1.481     raeburn  15539: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15540: (a) files in /uploaded
                   15541:   (i) If a local copy of the file exists - 
                   15542:       compares modification date of local copy with last-modified date for 
                   15543:       definitive version stored on home server for course. If local copy is 
                   15544:       stale, requests a new version from the home server and stores it. 
                   15545:       If the original has been removed from the home server, then local copy 
                   15546:       is unlinked.
                   15547:   (ii) If local copy does not exist -
                   15548:       requests the file from the home server and stores it. 
                   15549:   
                   15550:   If $caller is 'uploadrep':  
                   15551:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15552:     for request for files originally uploaded via DOCS. 
                   15553:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15554:   
                   15555:   Otherwise:
                   15556:      This indicates a call from the content generation phase of the request.
                   15557:      -  returns the entire contents of the file or -1.
                   15558:      
                   15559: (b) files in /res
                   15560:    - returns the entire contents of a file or -1; 
                   15561:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15562: 
1.712     albertel 15563: 
                   15564: =item *
                   15565: 
                   15566: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15567:                   reference
                   15568: 
                   15569: returns either a stat() list of data about the file or an empty list
                   15570: if the file doesn't exist or couldn't find out about it (connection
                   15571: problems or user unknown)
                   15572: 
1.191     harris41 15573: =item *
                   15574: 
1.243     albertel 15575: filelocation($dir,$file) : returns file system location of a file
                   15576: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15577: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15578: and a file of ../bob will become /a/bob)
1.191     harris41 15579: 
                   15580: =item *
                   15581: 
                   15582: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15583: filelocation except for hrefs
                   15584: 
                   15585: =item *
                   15586: 
1.1172.2.49  raeburn  15587: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15588: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15589: 
1.243     albertel 15590: =back
                   15591: 
1.608     albertel 15592: =head2 Usererfile file routines (/uploaded*)
                   15593: 
                   15594: =over 4
                   15595: 
                   15596: =item *
                   15597: 
                   15598: userfileupload(): main rotine for putting a file in a user or course's
                   15599:                   filespace, arguments are,
                   15600: 
1.620     albertel 15601:  formname - required - this is the name of the element in $env where the
1.608     albertel 15602:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15603:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15604:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15605:  context - if coursedoc, store the file in the course of the active role
                   15606:              of the current user; 
                   15607:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15608:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15609:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15610:          if undefined, it will be placed in "unknown"
                   15611: 
                   15612:  (This routine calls clean_filename() to remove any dangerous
                   15613:  characters from the filename, and then calls finuserfileupload() to
                   15614:  complete the transaction)
                   15615: 
                   15616:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15617:  and /adm/notfound.html if unsuccessful
                   15618: 
                   15619: =item *
                   15620: 
                   15621: clean_filename(): routine for cleaing a filename up for storage in
                   15622:                  userfile space, argument is:
                   15623: 
                   15624:  filename - proposed filename
                   15625: 
                   15626: returns: the new clean filename
                   15627: 
                   15628: =item *
                   15629: 
1.1090    raeburn  15630: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15631: userspace, probably shouldn't be called directly
                   15632: 
                   15633:   docuname: username or courseid of destination for the file
                   15634:   docudom: domain of user/course of destination for the file
                   15635:   formname: same as for userfileupload()
1.1090    raeburn  15636:   fname: filename (including subdirectories) for the file
                   15637:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15638:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15639:   allfiles: reference to hash used to store objects found by parser
                   15640:   codebase: reference to hash used for codebases of java objects found by parser
                   15641:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15642:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15643:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15644:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15645:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15646:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15647:   mimetype: reference to scalar to accommodate mime type determined
                   15648:             from File::MMagic if $parser = parse.
1.608     albertel 15649: 
                   15650:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15651:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15652:  was 'overwrite').
                   15653:  
1.608     albertel 15654: 
                   15655: =item *
                   15656: 
                   15657: renameuserfile(): renames an existing userfile to a new name
                   15658: 
                   15659:   Args:
                   15660:    docuname: username or courseid of destination for the file
                   15661:    docudom: domain of user/course of destination for the file
                   15662:    old: current file name (including any subdirs under userfiles)
                   15663:    new: desired file name (including any subdirs under userfiles)
                   15664: 
                   15665: =item *
                   15666: 
                   15667: mkdiruserfile(): creates a directory is a userfiles dir
                   15668: 
                   15669:   Args:
                   15670:    docuname: username or courseid of destination for the file
                   15671:    docudom: domain of user/course of destination for the file
                   15672:    dir: dir to create (including any subdirs under userfiles)
                   15673: 
                   15674: =item *
                   15675: 
                   15676: removeuserfile(): removes a file that exists in userfiles
                   15677: 
                   15678:   Args:
                   15679:    docuname: username or courseid of destination for the file
                   15680:    docudom: domain of user/course of destination for the file
                   15681:    fname: filname to delete (including any subdirs under userfiles)
                   15682: 
                   15683: =item *
                   15684: 
                   15685: removeuploadedurl(): convience function for removeuserfile()
                   15686: 
                   15687:   Args:
                   15688:    url:  a full /uploaded/... url to delete
                   15689: 
1.747     albertel 15690: =item * 
                   15691: 
                   15692: get_portfile_permissions():
                   15693:   Args:
                   15694:     domain: domain of user or course contain the portfolio files
                   15695:     user: name of user or num of course contain the portfolio files
                   15696:   Returns:
                   15697:     hashref of a dump of the proper file_permissions.db
                   15698:    
                   15699: 
                   15700: =item * 
                   15701: 
                   15702: get_access_controls():
                   15703: 
                   15704: Args:
                   15705:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15706:   group: (optional) the group you want the files associated with
                   15707:   file: (optional) the file you want access info on
                   15708: 
                   15709: Returns:
1.749     raeburn  15710:     a hash (keys are file names) of hashes containing
                   15711:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15712:         values are XML containing access control settings (see below) 
1.747     albertel 15713: 
                   15714: Internal notes:
                   15715: 
1.749     raeburn  15716:  access controls are stored in file_permissions.db as key=value pairs.
                   15717:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15718:         where scope -> public,guest,course,group,domains or users.
                   15719:               end -> UNIX time for end of access (0 -> no end date)
                   15720:               start -> UNIX time for start of access
                   15721: 
                   15722:     value -> XML description of access control
                   15723:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15724:             <start></start>
                   15725:             <end></end>
                   15726: 
                   15727:             <password></password>  for scope type = guest
                   15728: 
                   15729:             <domain></domain>     for scope type = course or group
                   15730:             <number></number>
                   15731:             <roles id="">
                   15732:              <role></role>
                   15733:              <access></access>
                   15734:              <section></section>
                   15735:              <group></group>
                   15736:             </roles>
                   15737: 
                   15738:             <dom></dom>         for scope type = domains
                   15739: 
                   15740:             <users>             for scope type = users
                   15741:              <user>
                   15742:               <uname></uname>
                   15743:               <udom></udom>
                   15744:              </user>
                   15745:             </users>
                   15746:            </scope> 
                   15747:               
                   15748:  Access data is also aggregated for each file in an additional key=value pair:
                   15749:  key -> path to file/file_name\0accesscontrol 
                   15750:  value -> reference to hash
                   15751:           hash contains key = value pairs
                   15752:           where key = uniqueID:scope_end_start
                   15753:                 value = UNIX time record was last updated
                   15754: 
                   15755:           Used to improve speed of look-ups of access controls for each file.  
                   15756:  
                   15757:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15758: 
1.1172.2.13  raeburn  15759: =item *
                   15760: 
1.749     raeburn  15761: modify_access_controls():
                   15762: 
                   15763: Modifies access controls for a portfolio file
                   15764: Args
                   15765: 1. file name
                   15766: 2. reference to hash of required changes,
                   15767: 3. domain
                   15768: 4. username
                   15769:   where domain,username are the domain of the portfolio owner 
                   15770:   (either a user or a course) 
                   15771: 
                   15772: Returns:
                   15773: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15774: 2. result of deletions ('ok' or 'error', with error message).
                   15775: 3. reference to hash of any new or updated access controls.
                   15776: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15777:    key = integer (inbound ID)
1.1172.2.13  raeburn  15778:    value = uniqueID
                   15779: 
                   15780: =item *
                   15781: 
                   15782: get_timebased_id():
                   15783: 
                   15784: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15785: course via the Course Editor (e.g., folders, composite pages,
                   15786: group bulletin boards).
                   15787: 
                   15788: Args: (first three required; six others optional)
                   15789: 
                   15790: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15791:    docssequence, or name of group
                   15792: 
                   15793: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15794:    e.g., num, boardids
                   15795: 
                   15796: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15797:    file will be named nohist_namespace.db
                   15798: 
                   15799: 4. cdom: domain of course; default is current course domain from %env
                   15800: 
                   15801: 5. cnum: course number; default is current course number from %env
                   15802: 
                   15803: 6. idtype: set to concat if an additional digit is to be appended to the
                   15804:    unix timestamp to form the suffix, if the plain timestamp is already
                   15805:    in use.  Default is to not do this, but simply increment the unix
                   15806:    timestamp by 1 until a unique key is obtained.
                   15807: 
                   15808: 7. who: holder of locking key; defaults to user:domain for user.
                   15809: 
                   15810: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15811:    retrying); default is 3.
                   15812: 
                   15813: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15814: 
                   15815: Returns:
                   15816: 
                   15817: 1. suffix obtained (numeric)
                   15818: 
                   15819: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15820: 
                   15821: 3. error: contains (localized) error message if an error occurred.
                   15822: 
1.747     albertel 15823: 
1.608     albertel 15824: =back
                   15825: 
1.243     albertel 15826: =head2 HTTP Helper Routines
                   15827: 
                   15828: =over 4
                   15829: 
1.191     harris41 15830: =item *
                   15831: 
                   15832: escape() : unpack non-word characters into CGI-compatible hex codes
                   15833: 
                   15834: =item *
                   15835: 
                   15836: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15837: 
1.243     albertel 15838: =back
                   15839: 
                   15840: =head1 PRIVATE SUBROUTINES
                   15841: 
                   15842: =head2 Underlying communication routines (Shouldn't call)
                   15843: 
                   15844: =over 4
                   15845: 
                   15846: =item *
                   15847: 
                   15848: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15849: 
                   15850: =item *
                   15851: 
                   15852: reply() : uses subreply to send a message to remote machine, logs all failures
                   15853: 
                   15854: =item *
                   15855: 
                   15856: critical() : passes a critical message to another server; if cannot
                   15857: get through then place message in connection buffer directory and
                   15858: returns con_delayed, if incapable of saving message, returns
                   15859: con_failed
                   15860: 
                   15861: =item *
                   15862: 
                   15863: reconlonc() : tries to reconnect lonc client processes.
                   15864: 
                   15865: =back
                   15866: 
                   15867: =head2 Resource Access Logging
                   15868: 
                   15869: =over 4
                   15870: 
                   15871: =item *
                   15872: 
                   15873: flushcourselogs() : flush (save) buffer logs and access logs
                   15874: 
                   15875: =item *
                   15876: 
                   15877: courselog($what) : save message for course in hash
                   15878: 
                   15879: =item *
                   15880: 
                   15881: courseacclog($what) : save message for course using &courselog().  Perform
                   15882: special processing for specific resource types (problems, exams, quizzes, etc).
                   15883: 
1.191     harris41 15884: =item *
                   15885: 
                   15886: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15887: as a PerlChildExitHandler
1.243     albertel 15888: 
                   15889: =back
                   15890: 
                   15891: =head2 Other
                   15892: 
                   15893: =over 4
                   15894: 
                   15895: =item *
                   15896: 
                   15897: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15898: 
                   15899: =back
                   15900: 
                   15901: =cut
1.877     foxr     15902: 

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