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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.135! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.134 2021/01/04 03:55:50 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:     }
                   1379:     if (($canhost) && ($uint_dom)) {
                   1380:         my @intdoms;
                   1381:         my $internet_names = &get_internet_names($try_server);
                   1382:         if (ref($internet_names) eq 'ARRAY') {
                   1383:             @intdoms = @{$internet_names};
                   1384:         }
                   1385:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1386:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1387:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1388:                                          $remotesessions,
                   1389:                                          $defdomdefaults{'hostedsessions'});
                   1390:         }
1.1083    raeburn  1391:     }
                   1392:     return $canhost;
                   1393: }
                   1394: 
1.1123    raeburn  1395: sub this_host_spares {
                   1396:     my ($dom) = @_;
1.1126    raeburn  1397:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1398:     my @hosts = &current_machine_ids();
                   1399:     foreach my $lonhost (@hosts) {
                   1400:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1401:             $dom_in_use = $dom;
                   1402:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1403:             last;
                   1404:         }
                   1405:     }
1.1126    raeburn  1406:     if ($dom_in_use ne '') {
                   1407:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1408:     }
                   1409:     if (ref($result) ne 'HASH') {
                   1410:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1411:         $dom_in_use = &host_domain($lonhost_in_use);
                   1412:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1413:         if (ref($result) ne 'HASH') {
                   1414:             $result = \%spareid;
                   1415:         }
                   1416:     }
                   1417:     return $result;
                   1418: }
                   1419: 
                   1420: sub spares_for_offload  {
                   1421:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1422:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1423:     if (defined($cached)) {
                   1424:         return $result;
                   1425:     } else {
1.1126    raeburn  1426:         my $cachetime = 60*60*24;
                   1427:         my %domconfig =
                   1428:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1429:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1430:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1431:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1432:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1433:                 }
                   1434:             }
                   1435:         }
                   1436:     }
1.1126    raeburn  1437:     return;
1.1123    raeburn  1438: }
                   1439: 
1.1129    raeburn  1440: sub get_lonbalancer_config {
                   1441:     my ($servers) = @_;
                   1442:     my ($currbalancer,$currtargets);
                   1443:     if (ref($servers) eq 'HASH') {
                   1444:         foreach my $server (keys(%{$servers})) {
                   1445:             my %what = (
                   1446:                          spareid => 1,
                   1447:                          perlvar => 1,
                   1448:                        );
                   1449:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1450:             if ($result eq 'ok') {
                   1451:                 if (ref($returnhash) eq 'HASH') {
                   1452:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1453:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1454:                             $currbalancer = $server;
                   1455:                             $currtargets = {};
                   1456:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1457:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1458:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1459:                                 }
                   1460:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1461:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1462:                                 }
                   1463:                             }
                   1464:                             last;
                   1465:                         }
                   1466:                     }
                   1467:                 }
                   1468:             }
                   1469:         }
                   1470:     }
                   1471:     return ($currbalancer,$currtargets);
                   1472: }
                   1473: 
                   1474: sub check_loadbalancing {
1.1172.2.88  raeburn  1475:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1476:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1477:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1478:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1479:     my @hosts = &current_machine_ids();
1.1129    raeburn  1480:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1481:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1482:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1483:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1484:     my $domneedscache; 
1.1129    raeburn  1485:     my $cachetime = 60*60*24;
                   1486: 
                   1487:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1488:         $dom_in_use = $udom;
                   1489:         $homeintdom = 1;
                   1490:     } else {
                   1491:         $dom_in_use = $serverhomedom;
                   1492:     }
                   1493:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1494:     unless (defined($cached)) {
                   1495:         my %domconfig =
                   1496:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1497:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1498:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1499:         } else {
                   1500:             $domneedscache = $dom_in_use;
1.1129    raeburn  1501:         }
                   1502:     }
                   1503:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1504:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1505:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1506:         if ($is_balancer) {
                   1507:             if (ref($currrules) eq 'HASH') {
                   1508:                 if ($homeintdom) {
                   1509:                     if ($uname ne '') {
                   1510:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1511:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1512:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1513:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1514:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1515:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1516:                             }
                   1517:                         }
                   1518:                         if ($rule_in_effect eq '') {
                   1519:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1520:                             if ($userenv{'inststatus'} ne '') {
                   1521:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1522:                                 my ($othertitle,$usertypes,$types) =
                   1523:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1524:                                 if (ref($types) eq 'ARRAY') {
                   1525:                                     foreach my $type (@{$types}) {
                   1526:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1527:                                             if (exists($currrules->{$type})) {
                   1528:                                                 $rule_in_effect = $currrules->{$type};
                   1529:                                             }
                   1530:                                         }
                   1531:                                     }
                   1532:                                 }
                   1533:                             } else {
                   1534:                                 if (exists($currrules->{'default'})) {
                   1535:                                     $rule_in_effect = $currrules->{'default'};
                   1536:                                 }
                   1537:                             }
                   1538:                         }
                   1539:                     } else {
                   1540:                         if (exists($currrules->{'default'})) {
                   1541:                             $rule_in_effect = $currrules->{'default'};
                   1542:                         }
                   1543:                     }
                   1544:                 } else {
                   1545:                     if ($currrules->{'_LC_external'} ne '') {
                   1546:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1547:                     }
                   1548:                 }
                   1549:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1550:                                                        $uname,$udom);
                   1551:             }
                   1552:         }
                   1553:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1554:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1555:         unless (defined($cached)) {
                   1556:             my %domconfig =
                   1557:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1558:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1559:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1560:             } else {
                   1561:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1562:             }
                   1563:         }
                   1564:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1565:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1566:                 &check_balancer_result($result,@hosts);
                   1567:             if ($is_balancer) {
1.1129    raeburn  1568:                 if (ref($currrules) eq 'HASH') {
                   1569:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1570:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1571:                     }
                   1572:                 }
                   1573:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1574:                                                        $uname,$udom);
                   1575:             }
                   1576:         } else {
                   1577:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1578:                 $is_balancer = 1;
                   1579:                 $offloadto = &this_host_spares($dom_in_use);
                   1580:             }
1.1172.2.75  raeburn  1581:             unless (defined($cached)) {
                   1582:                 $domneedscache = $serverhomedom;
                   1583:             }
1.1129    raeburn  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:         }
                   1593:     }
                   1594:     if ($domneedscache) {
                   1595:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1596:     }
1.1172.2.130  raeburn  1597:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1598:         my $lowest_load = 30000;
                   1599:         if (ref($offloadto) eq 'HASH') {
                   1600:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1601:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1602:                     ($otherserver,$lowest_load) =
                   1603:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1604:                 }
1.1129    raeburn  1605:             }
1.1172.2.5  raeburn  1606:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1607: 
1.1172.2.5  raeburn  1608:             if (!$found_server) {
                   1609:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1610:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1611:                         ($otherserver,$lowest_load) =
                   1612:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1613:                     }
                   1614:                 }
                   1615:             }
                   1616:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1617:             if (@{$offloadto} == 1) {
                   1618:                 $otherserver = $offloadto->[0];
                   1619:             } elsif (@{$offloadto} > 1) {
                   1620:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1621:                     ($otherserver,$lowest_load) =
                   1622:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1623:                 }
                   1624:             }
                   1625:         }
1.1172.2.88  raeburn  1626:         unless ($caller eq 'login') {
                   1627:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1628:                 $is_balancer = 0;
                   1629:                 if ($uname ne '' && $udom ne '') {
                   1630:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1631:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1632:                                  'user.loadbalcheck.time' => time});
                   1633:                     }
1.1172.2.5  raeburn  1634:                 }
1.1129    raeburn  1635:             }
                   1636:         }
1.1172.2.130  raeburn  1637:     }
                   1638:     if (($is_balancer) && (!$homeintdom)) {
                   1639:         undef($setcookie);
1.1129    raeburn  1640:     }
1.1172.2.107  raeburn  1641:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1642: }
                   1643: 
1.1172.2.12  raeburn  1644: sub check_balancer_result {
                   1645:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1646:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1647:     if (ref($result) eq 'HASH') {
                   1648:         if ($result->{'lonhost'} ne '') {
                   1649:             my $currbalancer = $result->{'lonhost'};
                   1650:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1651:                 $is_balancer = 1;
                   1652:                 $currtargets = $result->{'targets'};
                   1653:                 $currrules = $result->{'rules'};
                   1654:             }
                   1655:         } else {
                   1656:             foreach my $key (keys(%{$result})) {
                   1657:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1658:                     (ref($result->{$key}) eq 'HASH')) {
                   1659:                     $is_balancer = 1;
                   1660:                     $currrules = $result->{$key}{'rules'};
                   1661:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1662:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1663:                     last;
                   1664:                 }
                   1665:             }
                   1666:         }
                   1667:     }
1.1172.2.107  raeburn  1668:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1669: }
                   1670: 
1.1129    raeburn  1671: sub get_loadbalancer_targets {
                   1672:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1673:     my $offloadto;
1.1172.2.4  raeburn  1674:     if ($rule_in_effect eq 'none') {
                   1675:         return [$perlvar{'lonHostID'}];
                   1676:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1677:         $offloadto = $currtargets;
                   1678:     } else {
                   1679:         if ($rule_in_effect eq 'homeserver') {
                   1680:             my $homeserver = &homeserver($uname,$udom);
                   1681:             if ($homeserver ne 'no_host') {
                   1682:                 $offloadto = [$homeserver];
                   1683:             }
                   1684:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1685:             my %domconfig =
                   1686:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1687:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1688:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1689:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1690:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1691:                     }
                   1692:                 }
                   1693:             } else {
1.1172.2.7  raeburn  1694:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1695:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1696:                 if (&hostname($remotebalancer) ne '') {
                   1697:                     $offloadto = [$remotebalancer];
                   1698:                 }
                   1699:             }
                   1700:         } elsif (&hostname($rule_in_effect) ne '') {
                   1701:             $offloadto = [$rule_in_effect];
                   1702:         }
                   1703:     }
                   1704:     return $offloadto;
                   1705: }
                   1706: 
1.1127    raeburn  1707: sub internet_dom_servers {
                   1708:     my ($dom) = @_;
                   1709:     my (%uniqservers,%servers);
                   1710:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1711:     my @machinedoms = &machine_domains($primaryserver);
                   1712:     foreach my $mdom (@machinedoms) {
                   1713:         my %currservers = %servers;
                   1714:         my %server = &get_servers($mdom);
                   1715:         %servers = (%currservers,%server);
                   1716:     }
                   1717:     my %by_hostname;
                   1718:     foreach my $id (keys(%servers)) {
                   1719:         push(@{$by_hostname{$servers{$id}}},$id);
                   1720:     }
                   1721:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1722:         if (@{$by_hostname{$hostname}} > 1) {
                   1723:             my $match = 0;
                   1724:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1725:                 if (&host_domain($id) eq $dom) {
                   1726:                     $uniqservers{$id} = $hostname;
                   1727:                     $match = 1;
                   1728:                 }
                   1729:             }
                   1730:             unless ($match) {
                   1731:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1732:             }
                   1733:         } else {
                   1734:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1735:         }
                   1736:     }
                   1737:     return %uniqservers;
                   1738: }
                   1739: 
1.1       albertel 1740: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1741: 
1.599     albertel 1742: my %homecache;
1.1       albertel 1743: sub homeserver {
1.230     stredwic 1744:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1745:     my $index="$uname:$udom";
1.426     albertel 1746: 
1.599     albertel 1747:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1748: 
                   1749:     my %servers = &get_servers($udom,'library');
                   1750:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1751:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1752: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1753: 
                   1754: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1755: 	if ($answer eq 'found') {
                   1756: 	    delete($badServerCache{$tryserver}); 
                   1757: 	    return $homecache{$index}=$tryserver;
                   1758: 	} elsif ($answer eq 'no_host') {
                   1759: 	    $badServerCache{$tryserver}=1;
                   1760: 	}
1.1       albertel 1761:     }    
                   1762:     return 'no_host';
1.70      www      1763: }
                   1764: 
                   1765: # ------------------------------------- Find the usernames behind a list of IDs
                   1766: 
                   1767: sub idget {
                   1768:     my ($udom,@ids)=@_;
                   1769:     my %returnhash=();
                   1770:     
1.841     albertel 1771:     my %servers = &get_servers($udom,'library');
                   1772:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1773: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1774: 	$idlist=~tr/A-Z/a-z/; 
                   1775: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1776: 	my @answer=();
                   1777: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1778: 	    @answer=split(/\&/,$reply);
                   1779: 	}                    ;
                   1780: 	my $i;
                   1781: 	for ($i=0;$i<=$#ids;$i++) {
                   1782: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1783: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1784: 	    } 
                   1785: 	}
                   1786:     } 
1.70      www      1787:     return %returnhash;
                   1788: }
                   1789: 
                   1790: # ------------------------------------- Find the IDs behind a list of usernames
                   1791: 
                   1792: sub idrget {
                   1793:     my ($udom,@unames)=@_;
                   1794:     my %returnhash=();
1.800     albertel 1795:     foreach my $uname (@unames) {
                   1796:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1797:     }
1.70      www      1798:     return %returnhash;
                   1799: }
                   1800: 
                   1801: # ------------------------------- Store away a list of names and associated IDs
                   1802: 
                   1803: sub idput {
                   1804:     my ($udom,%ids)=@_;
                   1805:     my %servers=();
1.800     albertel 1806:     foreach my $uname (keys(%ids)) {
                   1807: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1808:         my $uhom=&homeserver($uname,$udom);
1.70      www      1809:         if ($uhom ne 'no_host') {
1.800     albertel 1810:             my $id=&escape($ids{$uname});
1.70      www      1811:             $id=~tr/A-Z/a-z/;
1.800     albertel 1812:             my $esc_unam=&escape($uname);
1.70      www      1813: 	    if ($servers{$uhom}) {
1.800     albertel 1814: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1815:             } else {
1.800     albertel 1816:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1817:             }
                   1818:         }
1.191     harris41 1819:     }
1.800     albertel 1820:     foreach my $server (keys(%servers)) {
                   1821:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1822:     }
1.344     www      1823: }
                   1824: 
1.1172.2.30  raeburn  1825: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1826: 
                   1827: sub iddel {
                   1828:     my ($udom,$idshashref,$uhome)=@_;
                   1829:     my %result=();
                   1830:     unless (ref($idshashref) eq 'HASH') {
                   1831:         return %result;
                   1832:     }
                   1833:     my %servers=();
                   1834:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1835:         my $uhom;
                   1836:         if ($uhome) {
                   1837:             $uhom = $uhome;
                   1838:         } else {
                   1839:             $uhom=&homeserver($uname,$udom);
                   1840:         }
                   1841:         if ($uhom ne 'no_host') {
                   1842:             if ($servers{$uhom}) {
                   1843:                 $servers{$uhom}.='&'.&escape($id);
                   1844:             } else {
                   1845:                 $servers{$uhom}=&escape($id);
                   1846:             }
                   1847:         }
                   1848:     }
                   1849:     foreach my $server (keys(%servers)) {
                   1850:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1851:     }
                   1852:     return %result;
                   1853: }
                   1854: 
1.1023    raeburn  1855: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1856: sub dump_dom {
1.1165    droeschl 1857:     my ($namespace, $udom, $regexp) = @_;
                   1858: 
                   1859:     $udom ||= $env{'user.domain'};
                   1860: 
                   1861:     return () unless $udom;
                   1862: 
                   1863:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1864: }
                   1865: 
1.1023    raeburn  1866: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1867: 
                   1868: sub get_dom {
1.860     raeburn  1869:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1870:     return if ($udom eq 'public');
1.806     raeburn  1871:     my $items='';
                   1872:     foreach my $item (@$storearr) {
                   1873:         $items.=&escape($item).'&';
                   1874:     }
                   1875:     $items=~s/\&$//;
1.860     raeburn  1876:     if (!$udom) {
                   1877:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1878:         return if ($udom eq 'public');
1.860     raeburn  1879:         if (defined(&domain($udom,'primary'))) {
                   1880:             $uhome=&domain($udom,'primary');
                   1881:         } else {
1.874     albertel 1882:             undef($uhome);
1.860     raeburn  1883:         }
                   1884:     } else {
                   1885:         if (!$uhome) {
                   1886:             if (defined(&domain($udom,'primary'))) {
                   1887:                 $uhome=&domain($udom,'primary');
                   1888:             }
                   1889:         }
                   1890:     }
                   1891:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1892:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1893:         my %returnhash;
1.875     albertel 1894:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1895:             return %returnhash;
                   1896:         }
1.806     raeburn  1897:         my @pairs=split(/\&/,$rep);
                   1898:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1899:             return @pairs;
                   1900:         }
                   1901:         my $i=0;
                   1902:         foreach my $item (@$storearr) {
                   1903:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1904:             $i++;
                   1905:         }
                   1906:         return %returnhash;
                   1907:     } else {
1.880     banghart 1908:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1909:     }
                   1910: }
                   1911: 
                   1912: # -------------------------------------------- put items in domain db files 
                   1913: 
                   1914: sub put_dom {
1.860     raeburn  1915:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1916:     if (!$udom) {
                   1917:         $udom=$env{'user.domain'};
                   1918:         if (defined(&domain($udom,'primary'))) {
                   1919:             $uhome=&domain($udom,'primary');
                   1920:         } else {
1.874     albertel 1921:             undef($uhome);
1.860     raeburn  1922:         }
                   1923:     } else {
                   1924:         if (!$uhome) {
                   1925:             if (defined(&domain($udom,'primary'))) {
                   1926:                 $uhome=&domain($udom,'primary');
                   1927:             }
                   1928:         }
                   1929:     } 
                   1930:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1931:         my $items='';
                   1932:         foreach my $item (keys(%$storehash)) {
                   1933:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1934:         }
                   1935:         $items=~s/\&$//;
                   1936:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1937:     } else {
1.860     raeburn  1938:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1939:     }
                   1940: }
                   1941: 
1.1023    raeburn  1942: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1943: sub newput_dom {
1.1023    raeburn  1944:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1945:     my $result;
                   1946:     if (!$udom) {
                   1947:         $udom=$env{'user.domain'};
                   1948:     }
1.1023    raeburn  1949:     if ($udom) {
                   1950:         my $uname = &get_domainconfiguser($udom);
                   1951:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1952:     }
                   1953:     return $result;
                   1954: }
                   1955: 
1.1023    raeburn  1956: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1957: sub del_dom {
1.1023    raeburn  1958:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1959:     if (ref($storearr) eq 'ARRAY') {
                   1960:         if (!$udom) {
                   1961:             $udom=$env{'user.domain'};
                   1962:         }
1.1023    raeburn  1963:         if ($udom) {
                   1964:             my $uname = &get_domainconfiguser($udom); 
                   1965:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1966:         }
                   1967:     }
                   1968: }
                   1969: 
1.1023    raeburn  1970: # ----------------------------------construct domainconfig user for a domain 
                   1971: sub get_domainconfiguser {
                   1972:     my ($udom) = @_;
                   1973:     return $udom.'-domainconfig';
                   1974: }
                   1975: 
1.837     raeburn  1976: sub retrieve_inst_usertypes {
                   1977:     my ($udom) = @_;
                   1978:     my (%returnhash,@order);
1.989     raeburn  1979:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1980:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1981:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1982:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1983:     } else {
                   1984:         if (defined(&domain($udom,'primary'))) {
                   1985:             my $uhome=&domain($udom,'primary');
                   1986:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1987:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1988:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1989:                 return (\%returnhash,\@order);
                   1990:             }
                   1991:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1992:             my @pairs=split(/\&/,$hashitems);
                   1993:             foreach my $item (@pairs) {
                   1994:                 my ($key,$value)=split(/=/,$item,2);
                   1995:                 $key = &unescape($key);
                   1996:                 next if ($key =~ /^error: 2 /);
                   1997:                 $returnhash{$key}=&thaw_unescape($value);
                   1998:             }
                   1999:             my @esc_order = split(/\&/,$orderitems);
                   2000:             foreach my $item (@esc_order) {
                   2001:                 push(@order,&unescape($item));
                   2002:             }
                   2003:         } else {
1.1172.2.44  raeburn  2004:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2005:         }
1.1172.2.44  raeburn  2006:         return (\%returnhash,\@order);
1.837     raeburn  2007:     }
                   2008: }
                   2009: 
1.868     raeburn  2010: sub is_domainimage {
                   2011:     my ($url) = @_;
1.1172.2.74  raeburn  2012:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2013:         if (&domain($1) ne '') {
                   2014:             return '1';
                   2015:         }
                   2016:     }
                   2017:     return;
                   2018: }
                   2019: 
1.899     raeburn  2020: sub inst_directory_query {
                   2021:     my ($srch) = @_;
                   2022:     my $udom = $srch->{'srchdomain'};
                   2023:     my %results;
                   2024:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2025:     my $outcome;
1.899     raeburn  2026:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2027:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2028:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2029:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2030:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2031:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2032:                     (($major == 2) && ($minor < 11)) ||
                   2033:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2034:                     return;
                   2035:                 }
                   2036:             }
                   2037:         }
1.904     albertel 2038: 	my $queryid=&reply("querysend:instdirsearch:".
                   2039: 			   &escape($srch->{'srchby'}).':'.
                   2040: 			   &escape($srch->{'srchterm'}).':'.
                   2041: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2042: 	my $host=&hostname($homeserver);
                   2043: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2044: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2045: 	    return;
                   2046: 	}
                   2047: 	my $response = &get_query_reply($queryid);
                   2048: 	my $maxtries = 5;
                   2049: 	my $tries = 1;
                   2050: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2051: 	    $response = &get_query_reply($queryid);
                   2052: 	    $tries ++;
                   2053: 	}
                   2054: 
                   2055:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2056:             if ($response eq 'unavailable') {
                   2057:                 $outcome = $response;
                   2058:             } else {
                   2059:                 $outcome = 'ok';
                   2060:                 my @matches = split(/\n/,$response);
                   2061:                 foreach my $match (@matches) {
                   2062:                     my ($key,$value) = split(/=/,$match);
                   2063:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2064:                 }
1.899     raeburn  2065:             }
                   2066:         }
                   2067:     }
1.909     raeburn  2068:     return ($outcome,%results);
1.899     raeburn  2069: }
                   2070: 
                   2071: sub usersearch {
                   2072:     my ($srch) = @_;
                   2073:     my $dom = $srch->{'srchdomain'};
                   2074:     my %results;
                   2075:     my %libserv = &all_library();
                   2076:     my $query = 'usersearch';
                   2077:     foreach my $tryserver (keys(%libserv)) {
                   2078:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2079:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2080:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2081:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2082:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2083:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2084:                              (($major == 2) && ($minor < 11)) ||
                   2085:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2086:                 }
                   2087:             }
1.899     raeburn  2088:             my $host=&hostname($tryserver);
                   2089:             my $queryid=
1.911     raeburn  2090:                 &reply("querysend:".&escape($query).':'.
                   2091:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2092:                        &escape($srch->{'srchtype'}).':'.
                   2093:                        &escape($srch->{'srchterm'}),$tryserver);
                   2094:             if ($queryid !~/^\Q$host\E\_/) {
                   2095:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2096:                 next;
1.899     raeburn  2097:             }
                   2098:             my $reply = &get_query_reply($queryid);
                   2099:             my $maxtries = 1;
                   2100:             my $tries = 1;
                   2101:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2102:                 $reply = &get_query_reply($queryid);
                   2103:                 $tries ++;
                   2104:             }
                   2105:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2106:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2107:             } else {
1.911     raeburn  2108:                 my @matches;
                   2109:                 if ($reply =~ /\n/) {
                   2110:                     @matches = split(/\n/,$reply);
                   2111:                 } else {
                   2112:                     @matches = split(/\&/,$reply);
                   2113:                 }
1.899     raeburn  2114:                 foreach my $match (@matches) {
                   2115:                     my ($uname,$udom,%userhash);
1.911     raeburn  2116:                     foreach my $entry (split(/:/,$match)) {
                   2117:                         my ($key,$value) =
                   2118:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2119:                         $userhash{$key} = $value;
                   2120:                         if ($key eq 'username') {
                   2121:                             $uname = $value;
                   2122:                         } elsif ($key eq 'domain') {
                   2123:                             $udom = $value;
1.911     raeburn  2124:                         }
1.899     raeburn  2125:                     }
                   2126:                     $results{$uname.':'.$udom} = \%userhash;
                   2127:                 }
                   2128:             }
                   2129:         }
                   2130:     }
                   2131:     return %results;
                   2132: }
                   2133: 
1.912     raeburn  2134: sub get_instuser {
                   2135:     my ($udom,$uname,$id) = @_;
                   2136:     my $homeserver = &domain($udom,'primary');
                   2137:     my ($outcome,%results);
                   2138:     if ($homeserver ne '') {
                   2139:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2140:                            &escape($id).':'.&escape($udom),$homeserver);
                   2141:         my $host=&hostname($homeserver);
                   2142:         if ($queryid !~/^\Q$host\E\_/) {
                   2143:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2144:             return;
                   2145:         }
                   2146:         my $response = &get_query_reply($queryid);
                   2147:         my $maxtries = 5;
                   2148:         my $tries = 1;
                   2149:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2150:             $response = &get_query_reply($queryid);
                   2151:             $tries ++;
                   2152:         }
                   2153:         if (!&error($response) && $response ne 'refused') {
                   2154:             if ($response eq 'unavailable') {
                   2155:                 $outcome = $response;
                   2156:             } else {
                   2157:                 $outcome = 'ok';
                   2158:                 my @matches = split(/\n/,$response);
                   2159:                 foreach my $match (@matches) {
                   2160:                     my ($key,$value) = split(/=/,$match);
                   2161:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2162:                 }
                   2163:             }
                   2164:         }
                   2165:     }
                   2166:     my %userinfo;
                   2167:     if (ref($results{$uname}) eq 'HASH') {
                   2168:         %userinfo = %{$results{$uname}};
                   2169:     } 
                   2170:     return ($outcome,%userinfo);
                   2171: }
                   2172: 
1.1172.2.69  raeburn  2173: sub get_multiple_instusers {
                   2174:     my ($udom,$users,$caller) = @_;
                   2175:     my ($outcome,$results);
                   2176:     if (ref($users) eq 'HASH') {
                   2177:         my $count = keys(%{$users});
                   2178:         my $requested = &freeze_escape($users);
                   2179:         my $homeserver = &domain($udom,'primary');
                   2180:         if ($homeserver ne '') {
                   2181:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2182:             my $host=&hostname($homeserver);
                   2183:             if ($queryid !~/^\Q$host\E\_/) {
                   2184:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2185:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2186:                 return ($outcome,$results);
                   2187:             }
                   2188:             my $response = &get_query_reply($queryid);
                   2189:             my $maxtries = 5;
                   2190:             if ($count > 100) {
                   2191:                 $maxtries = 1+int($count/20);
                   2192:             }
                   2193:             my $tries = 1;
                   2194:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2195:                 $response = &get_query_reply($queryid);
                   2196:                 $tries ++;
                   2197:             }
                   2198:             if ($response eq '') {
                   2199:                 $results = {};
                   2200:                 foreach my $key (keys(%{$users})) {
                   2201:                     my ($uname,$id);
                   2202:                     if ($caller eq 'id') {
                   2203:                         $id = $key;
                   2204:                     } else {
                   2205:                         $uname = $key;
                   2206:                     }
                   2207:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2208:                     $outcome = $resp;
                   2209:                     if ($resp eq 'ok') {
                   2210:                         %{$results} = (%{$results}, %info);
                   2211:                     } else {
                   2212:                         last;
                   2213:                     }
                   2214:                 }
                   2215:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2216:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2217:                     $outcome = $response;
                   2218:                 } else {
                   2219:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2220:                     if ($outcome eq 'ok') {
                   2221:                         $results = &thaw_unescape($userdata);
                   2222:                     }
                   2223:                 }
                   2224:             }
                   2225:         }
                   2226:     }
                   2227:     return ($outcome,$results);
                   2228: }
                   2229: 
1.912     raeburn  2230: sub inst_rulecheck {
1.923     raeburn  2231:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2232:     my %returnhash;
                   2233:     if ($udom ne '') {
                   2234:         if (ref($rules) eq 'ARRAY') {
                   2235:             @{$rules} = map {&escape($_);} (@{$rules});
                   2236:             my $rulestr = join(':',@{$rules});
                   2237:             my $homeserver=&domain($udom,'primary');
                   2238:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2239:                 my $response;
                   2240:                 if ($item eq 'username') {                
                   2241:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2242:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2243:                                               $homeserver));
1.923     raeburn  2244:                 } elsif ($item eq 'id') {
                   2245:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2246:                                               ':'.&escape($id).':'.$rulestr,
                   2247:                                               $homeserver));
1.945     raeburn  2248:                 } elsif ($item eq 'selfcreate') {
                   2249:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2250:                                                &escape($udom).':'.&escape($uname).
                   2251:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2252:                 }
1.912     raeburn  2253:                 if ($response ne 'refused') {
                   2254:                     my @pairs=split(/\&/,$response);
                   2255:                     foreach my $item (@pairs) {
                   2256:                         my ($key,$value)=split(/=/,$item,2);
                   2257:                         $key = &unescape($key);
                   2258:                         next if ($key =~ /^error: 2 /);
                   2259:                         $returnhash{$key}=&thaw_unescape($value);
                   2260:                     }
                   2261:                 }
                   2262:             }
                   2263:         }
                   2264:     }
                   2265:     return %returnhash;
                   2266: }
                   2267: 
                   2268: sub inst_userrules {
1.923     raeburn  2269:     my ($udom,$check) = @_;
1.912     raeburn  2270:     my (%ruleshash,@ruleorder);
                   2271:     if ($udom ne '') {
                   2272:         my $homeserver=&domain($udom,'primary');
                   2273:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2274:             my $response;
                   2275:             if ($check eq 'id') {
                   2276:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2277:                                  $homeserver);
1.943     raeburn  2278:             } elsif ($check eq 'email') {
                   2279:                 $response=&reply('instemailrules:'.&escape($udom),
                   2280:                                  $homeserver);
1.923     raeburn  2281:             } else {
                   2282:                 $response=&reply('instuserrules:'.&escape($udom),
                   2283:                                  $homeserver);
                   2284:             }
1.912     raeburn  2285:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2286:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2287:                 ($response ne 'no_such_host')) {
                   2288:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2289:                 my @pairs=split(/\&/,$hashitems);
                   2290:                 foreach my $item (@pairs) {
                   2291:                     my ($key,$value)=split(/=/,$item,2);
                   2292:                     $key = &unescape($key);
                   2293:                     next if ($key =~ /^error: 2 /);
                   2294:                     $ruleshash{$key}=&thaw_unescape($value);
                   2295:                 }
                   2296:                 my @esc_order = split(/\&/,$orderitems);
                   2297:                 foreach my $item (@esc_order) {
                   2298:                     push(@ruleorder,&unescape($item));
                   2299:                 }
                   2300:             }
                   2301:         }
                   2302:     }
                   2303:     return (\%ruleshash,\@ruleorder);
                   2304: }
                   2305: 
1.976     raeburn  2306: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2307: 
                   2308: sub get_domain_defaults {
1.1172.2.35  raeburn  2309:     my ($domain,$ignore_cache) = @_;
                   2310:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2311:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2312:     unless ($ignore_cache) {
                   2313:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2314:         if (defined($cached)) {
                   2315:             if (ref($result) eq 'HASH') {
                   2316:                 return %{$result};
                   2317:             }
1.943     raeburn  2318:         }
                   2319:     }
                   2320:     my %domdefaults;
                   2321:     my %domconfig =
1.989     raeburn  2322:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2323:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2324:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2325:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2326:                                   'coursecategories','autoenroll',
                   2327:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2328:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2329:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2330:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2331:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2332:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2333:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2334:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2335:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2336:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2337:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2338:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2339:     } else {
                   2340:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2341:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2342:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2343:     }
1.976     raeburn  2344:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2345:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2346:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2347:         } else {
                   2348:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2349:         }
1.1172.2.6  raeburn  2350:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2351:         foreach my $item (@usertools) {
                   2352:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2353:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2354:             }
                   2355:         }
1.1172.2.29  raeburn  2356:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2357:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2358:         }
1.976     raeburn  2359:     }
1.985     raeburn  2360:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2361:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2362:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2363:         }
                   2364:     }
1.1172.2.9  raeburn  2365:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2366:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2367:     }
1.989     raeburn  2368:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2369:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2370:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2371:         }
                   2372:     }
1.1047    raeburn  2373:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2374:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2375:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2376:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2377:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2378:         }
1.1172.2.41  raeburn  2379:         foreach my $type (@coursetypes) {
                   2380:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2381:                 unless ($type eq 'community') {
                   2382:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2383:                 }
                   2384:             }
                   2385:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2386:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2387:             }
1.1172.2.60  raeburn  2388:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2389:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2390:                     $domdefaults{$type.'postsubtimeout'} =
                   2391:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2392:                 }
                   2393:             }
1.1172.2.30  raeburn  2394:         }
1.1172.2.67  raeburn  2395:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2396:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2397:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2398:                 if (@clonecodes) {
                   2399:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2400:                 }
                   2401:             }
                   2402:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2403:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2404:         }
1.1172.2.103  raeburn  2405:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2406:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2407:         }
1.1047    raeburn  2408:     }
1.1073    raeburn  2409:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2410:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2411:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2412:         }
                   2413:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2414:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2415:         }
1.1172.2.62  raeburn  2416:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2417:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2418:         }
1.1073    raeburn  2419:     }
1.1172.2.41  raeburn  2420:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2421:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2422:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2423:                             'approval','limit');
                   2424:             foreach my $type (@coursetypes) {
                   2425:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2426:                     my @mgrdc = ();
                   2427:                     foreach my $item (@settings) {
                   2428:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2429:                             push(@mgrdc,$item);
                   2430:                         }
                   2431:                     }
                   2432:                     if (@mgrdc) {
                   2433:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2434:                     }
                   2435:                 }
                   2436:             }
                   2437:         }
                   2438:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2439:             foreach my $type (@coursetypes) {
                   2440:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2441:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2442:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2443:                     }
                   2444:                 }
                   2445:             }
                   2446:         }
                   2447:     }
1.1172.2.46  raeburn  2448:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2449:         $domdefaults{'catauth'} = 'std';
                   2450:         $domdefaults{'catunauth'} = 'std';
                   2451:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2452:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2453:         }
                   2454:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2455:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2456:         }
                   2457:     }
1.1172.2.76  raeburn  2458:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2459:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2460:     }
1.1172.2.89  raeburn  2461:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2462:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2463:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2464:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2465:         }
                   2466:     }
1.1172.2.23  raeburn  2467:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2468:     return %domdefaults;
                   2469: }
                   2470: 
1.1172.2.106  raeburn  2471: sub get_dom_cats {
                   2472:     my ($dom) = @_;
                   2473:     return unless (&domain($dom));
                   2474:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2475:     unless (defined($cached)) {
                   2476:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2477:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2478:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2479:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2480:             } else {
                   2481:                 $cats = {};
                   2482:             }
                   2483:         } else {
                   2484:             $cats = {};
                   2485:         }
                   2486:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2487:     }
                   2488:     return $cats;
                   2489: }
                   2490: 
                   2491: sub get_dom_instcats {
                   2492:     my ($dom) = @_;
                   2493:     return unless (&domain($dom));
                   2494:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2495:     unless (defined($cached)) {
                   2496:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2497:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2498:         if ($totcodes > 0) {
                   2499:             my $caller = 'global';
                   2500:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2501:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2502:                 $instcats = {
                   2503:                                 codes => \%codes,
                   2504:                                 codetitles => \@codetitles,
                   2505:                                 cat_titles => \%cat_titles,
                   2506:                                 cat_order => \%cat_order,
                   2507:                             };
                   2508:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2509:             }
                   2510:         }
                   2511:     }
                   2512:     return $instcats;
                   2513: }
                   2514: 
                   2515: sub retrieve_instcodes {
                   2516:     my ($coursecodes,$dom) = @_;
                   2517:     my $totcodes;
                   2518:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2519:     foreach my $course (keys(%courses)) {
                   2520:         if (ref($courses{$course}) eq 'HASH') {
                   2521:             if ($courses{$course}{'inst_code'} ne '') {
                   2522:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2523:                 $totcodes ++;
                   2524:             }
                   2525:         }
                   2526:     }
                   2527:     return $totcodes;
                   2528: }
                   2529: 
1.1172.2.113  raeburn  2530: # --------------------------------------------- Get domain config for passwords
                   2531: 
                   2532: sub get_passwdconf {
                   2533:     my ($dom) = @_;
                   2534:     my (%passwdconf,$gotconf,$lookup);
                   2535:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2536:     if (defined($cached)) {
                   2537:         if (ref($result) eq 'HASH') {
                   2538:             %passwdconf = %{$result};
                   2539:             $gotconf = 1;
                   2540:         }
                   2541:     }
                   2542:     unless ($gotconf) {
                   2543:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2544:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2545:             %passwdconf = %{$domconfig{'passwords'}};
                   2546:         }
                   2547:         my $cachetime = 24*60*60;
                   2548:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2549:     }
                   2550:     return %passwdconf;
                   2551: }
                   2552: 
1.344     www      2553: # --------------------------------------------------- Assign a key to a student
                   2554: 
                   2555: sub assign_access_key {
1.364     www      2556: #
                   2557: # a valid key looks like uname:udom#comments
                   2558: # comments are being appended
                   2559: #
1.498     www      2560:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2561:     $kdom=
1.620     albertel 2562:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2563:     $knum=
1.620     albertel 2564:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2565:     $cdom=
1.620     albertel 2566:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2567:     $cnum=
1.620     albertel 2568:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2569:     $udom=$env{'user.name'} unless (defined($udom));
                   2570:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2571:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2572:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2573:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2574:                                                   # assigned to this person
                   2575:                                                   # - this should not happen,
1.345     www      2576:                                                   # unless something went wrong
                   2577:                                                   # the first time around
                   2578: # ready to assign
1.364     www      2579:         $logentry=$1.'; '.$logentry;
1.496     www      2580:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2581:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2582: # key now belongs to user
1.346     www      2583: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2584:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2585:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2586:                 return 'ok';
                   2587:             } else {
                   2588:                 return 
                   2589:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2590: 	    }
                   2591:         } else {
                   2592:             return 'error: Could not assign key, try again later.';
                   2593:         }
1.364     www      2594:     } elsif (!$existing{$ckey}) {
1.345     www      2595: # the key does not exist
                   2596: 	return 'error: The key does not exist';
                   2597:     } else {
                   2598: # the key is somebody else's
                   2599: 	return 'error: The key is already in use';
                   2600:     }
1.344     www      2601: }
                   2602: 
1.364     www      2603: # ------------------------------------------ put an additional comment on a key
                   2604: 
                   2605: sub comment_access_key {
                   2606: #
                   2607: # a valid key looks like uname:udom#comments
                   2608: # comments are being appended
                   2609: #
                   2610:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2611:     $cdom=
1.620     albertel 2612:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2613:     $cnum=
1.620     albertel 2614:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2615:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2616:     if ($existing{$ckey}) {
                   2617:         $existing{$ckey}.='; '.$logentry;
                   2618: # ready to assign
1.367     www      2619:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2620:                                                  $cdom,$cnum) eq 'ok') {
                   2621: 	    return 'ok';
                   2622:         } else {
                   2623: 	    return 'error: Count not store comment.';
                   2624:         }
                   2625:     } else {
                   2626: # the key does not exist
                   2627: 	return 'error: The key does not exist';
                   2628:     }
                   2629: }
                   2630: 
1.344     www      2631: # ------------------------------------------------------ Generate a set of keys
                   2632: 
                   2633: sub generate_access_keys {
1.364     www      2634:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2635:     $cdom=
1.620     albertel 2636:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2637:     $cnum=
1.620     albertel 2638:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2639:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2640:     unless (($cdom) && ($cnum)) { return 0; }
                   2641:     if ($number>10000) { return 0; }
                   2642:     sleep(2); # make sure don't get same seed twice
                   2643:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2644:     my $total=0;
                   2645:     for (my $i=1;$i<=$number;$i++) {
                   2646:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2647:                   sprintf("%lx",int(100000*rand)).'-'.
                   2648:                   sprintf("%lx",int(100000*rand));
                   2649:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2650:        $newkey=~s/0/h/g; # and also 0 and O
                   2651:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2652:        if ($existing{$newkey}) {
                   2653:            $i--;
                   2654:        } else {
1.364     www      2655: 	  if (&put('accesskeys',
                   2656:               { $newkey => '# generated '.localtime().
1.620     albertel 2657:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2658:                            '; '.$logentry },
                   2659: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2660:               $total++;
                   2661: 	  }
                   2662:        }
                   2663:     }
1.620     albertel 2664:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2665:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2666:     return $total;
                   2667: }
                   2668: 
                   2669: # ------------------------------------------------------- Validate an accesskey
                   2670: 
                   2671: sub validate_access_key {
                   2672:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2673:     $cdom=
1.620     albertel 2674:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2675:     $cnum=
1.620     albertel 2676:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2677:     $udom=$env{'user.domain'} unless (defined($udom));
                   2678:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2679:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2680:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2681: }
                   2682: 
                   2683: # ------------------------------------- Find the section of student in a course
1.652     albertel 2684: sub devalidate_getsection_cache {
                   2685:     my ($udom,$unam,$courseid)=@_;
                   2686:     my $hashid="$udom:$unam:$courseid";
                   2687:     &devalidate_cache_new('getsection',$hashid);
                   2688: }
1.298     matthew  2689: 
1.815     albertel 2690: sub courseid_to_courseurl {
                   2691:     my ($courseid) = @_;
                   2692:     #already url style courseid
                   2693:     return $courseid if ($courseid =~ m{^/});
                   2694: 
                   2695:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2696: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2697: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2698: 	return "/$cdom/$cnum";
                   2699:     }
                   2700: 
                   2701:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2702:     if (exists($courseinfo{'num'})) {
                   2703: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2704:     }
                   2705: 
                   2706:     return undef;
                   2707: }
                   2708: 
1.298     matthew  2709: sub getsection {
                   2710:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2711:     my $cachetime=1800;
1.551     albertel 2712: 
                   2713:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2714:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2715:     if (defined($cached)) { return $result; }
                   2716: 
1.298     matthew  2717:     my %Pending; 
                   2718:     my %Expired;
                   2719:     #
                   2720:     # Each role can either have not started yet (pending), be active, 
                   2721:     #    or have expired.
                   2722:     #
                   2723:     # If there is an active role, we are done.
                   2724:     #
                   2725:     # If there is more than one role which has not started yet, 
                   2726:     #     choose the one which will start sooner
                   2727:     # If there is one role which has not started yet, return it.
                   2728:     #
                   2729:     # If there is more than one expired role, choose the one which ended last.
                   2730:     # If there is a role which has expired, return it.
                   2731:     #
1.815     albertel 2732:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2733:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2734:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2735:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2736:         my $section=$1;
                   2737:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2738:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2739:         my $now=time;
1.548     albertel 2740:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2741:             $Expired{$end}=$section;
                   2742:             next;
                   2743:         }
1.548     albertel 2744:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2745:             $Pending{$start}=$section;
                   2746:             next;
                   2747:         }
1.599     albertel 2748:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2749:     }
                   2750:     #
                   2751:     # Presumedly there will be few matching roles from the above
                   2752:     # loop and the sorting time will be negligible.
                   2753:     if (scalar(keys(%Pending))) {
                   2754:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2755:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2756:     } 
                   2757:     if (scalar(keys(%Expired))) {
                   2758:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2759:         my $time = pop(@sorted);
1.599     albertel 2760:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2761:     }
1.599     albertel 2762:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2763: }
1.70      www      2764: 
1.599     albertel 2765: sub save_cache {
                   2766:     &purge_remembered();
1.722     albertel 2767:     #&Apache::loncommon::validate_page();
1.620     albertel 2768:     undef(%env);
1.780     albertel 2769:     undef($env_loaded);
1.599     albertel 2770: }
1.452     albertel 2771: 
1.599     albertel 2772: my $to_remember=-1;
                   2773: my %remembered;
                   2774: my %accessed;
                   2775: my $kicks=0;
                   2776: my $hits=0;
1.849     albertel 2777: sub make_key {
                   2778:     my ($name,$id) = @_;
1.872     albertel 2779:     if (length($id) > 65 
                   2780: 	&& length(&escape($id)) > 200) {
                   2781: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2782:     }
1.849     albertel 2783:     return &escape($name.':'.$id);
                   2784: }
                   2785: 
1.599     albertel 2786: sub devalidate_cache_new {
                   2787:     my ($name,$id,$debug) = @_;
                   2788:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2789:     my $remembered_id=$name.':'.$id;
1.849     albertel 2790:     $id=&make_key($name,$id);
1.599     albertel 2791:     $memcache->delete($id);
1.1172.2.81  raeburn  2792:     delete($remembered{$remembered_id});
                   2793:     delete($accessed{$remembered_id});
1.599     albertel 2794: }
                   2795: 
                   2796: sub is_cached_new {
                   2797:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2798:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2799:                                      # keys in %remembered hash, which persists for
                   2800:                                      # duration of request (no restriction on key length).
                   2801:     if (exists($remembered{$remembered_id})) {
                   2802: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2803: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2804: 	$hits++;
1.1172.2.81  raeburn  2805: 	return ($remembered{$remembered_id},1);
1.599     albertel 2806:     }
1.1172.2.81  raeburn  2807:     $id=&make_key($name,$id);
1.599     albertel 2808:     my $value = $memcache->get($id);
                   2809:     if (!(defined($value))) {
                   2810: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2811: 	return (undef,undef);
1.416     albertel 2812:     }
1.599     albertel 2813:     if ($value eq '__undef__') {
                   2814: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2815: 	$value=undef;
                   2816:     }
1.1172.2.81  raeburn  2817:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2818:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2819:     return ($value,1);
                   2820: }
                   2821: 
                   2822: sub do_cache_new {
                   2823:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2824:     my $remembered_id=$name.':'.$id;
1.849     albertel 2825:     $id=&make_key($name,$id);
1.599     albertel 2826:     my $setvalue=$value;
                   2827:     if (!defined($setvalue)) {
                   2828: 	$setvalue='__undef__';
                   2829:     }
1.623     albertel 2830:     if (!defined($time) ) {
                   2831: 	$time=600;
                   2832:     }
1.599     albertel 2833:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2834:     my $result = $memcache->set($id,$setvalue,$time);
                   2835:     if (! $result) {
1.872     albertel 2836: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2837: 	$memcache->disconnect_all();
1.872     albertel 2838:     }
1.600     albertel 2839:     # need to make a copy of $value
1.1172.2.81  raeburn  2840:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2841:     return $value;
                   2842: }
                   2843: 
                   2844: sub make_room {
1.1172.2.81  raeburn  2845:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2846: 
1.1172.2.81  raeburn  2847:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2848:                                     : $value;
1.599     albertel 2849:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2850:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2851:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2852:     my $to_kick;
                   2853:     my $max_time=0;
                   2854:     foreach my $other (keys(%accessed)) {
                   2855: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2856: 	    $to_kick=$other;
                   2857: 	    $max_time=&tv_interval($accessed{$other});
                   2858: 	}
                   2859:     }
                   2860:     delete($remembered{$to_kick});
                   2861:     delete($accessed{$to_kick});
                   2862:     $kicks++;
                   2863:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2864:     return;
                   2865: }
                   2866: 
1.599     albertel 2867: sub purge_remembered {
1.604     albertel 2868:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2869:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2870:     undef(%remembered);
                   2871:     undef(%accessed);
1.428     albertel 2872: }
1.70      www      2873: # ------------------------------------- Read an entry from a user's environment
                   2874: 
                   2875: sub userenvironment {
                   2876:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2877:     my $items;
                   2878:     foreach my $item (@what) {
                   2879:         $items.=&escape($item).'&';
                   2880:     }
                   2881:     $items=~s/\&$//;
1.70      www      2882:     my %returnhash=();
1.1009    raeburn  2883:     my $uhome = &homeserver($unam,$udom);
                   2884:     unless ($uhome eq 'no_host') {
                   2885:         my @answer=split(/\&/, 
                   2886:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2887:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2888:             return %returnhash;
                   2889:         }
1.1009    raeburn  2890:         my $i;
                   2891:         for ($i=0;$i<=$#what;$i++) {
                   2892: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2893:         }
1.70      www      2894:     }
                   2895:     return %returnhash;
1.1       albertel 2896: }
                   2897: 
1.617     albertel 2898: # ---------------------------------------------------------- Get a studentphoto
                   2899: sub studentphoto {
                   2900:     my ($udom,$unam,$ext) = @_;
                   2901:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2902:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2903:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2904:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2905:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2906:             } else {
                   2907:                 my ($result,$perm_reqd)=
1.707     albertel 2908: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2909:                 if ($result eq 'ok') {
                   2910:                     if (!($perm_reqd eq 'yes')) {
                   2911:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2912:                     }
                   2913:                 }
                   2914:             }
                   2915:         }
                   2916:     } else {
                   2917:         my ($result,$perm_reqd) = 
1.707     albertel 2918: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2919:         if ($result eq 'ok') {
                   2920:             if (!($perm_reqd eq 'yes')) {
                   2921:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2922:             }
                   2923:         }
                   2924:     }
                   2925:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2926: }
                   2927: 
                   2928: sub retrievestudentphoto {
                   2929:     my ($udom,$unam,$ext,$type) = @_;
                   2930:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2931:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2932:     if ($ret eq 'ok') {
                   2933:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2934:         if ($type eq 'thumbnail') {
                   2935:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2936:         }
                   2937:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2938:         return $tokenurl;
                   2939:     } else {
                   2940:         if ($type eq 'thumbnail') {
                   2941:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2942:         } else { 
                   2943:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2944:         }
1.617     albertel 2945:     }
                   2946: }
                   2947: 
1.263     www      2948: # -------------------------------------------------------------------- New chat
                   2949: 
                   2950: sub chatsend {
1.724     raeburn  2951:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2952:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2953:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2954:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2955:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2956: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2957: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2958: }
                   2959: 
                   2960: # ------------------------------------------ Find current version of a resource
                   2961: 
                   2962: sub getversion {
                   2963:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2964:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2965:     return &currentversion(&filelocation('',$fname));
                   2966: }
                   2967: 
                   2968: sub currentversion {
                   2969:     my $fname=shift;
                   2970:     my $author=$fname;
                   2971:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2972:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2973:     my $home=&homeserver($uname,$udom);
1.292     www      2974:     if ($home eq 'no_host') { 
                   2975:         return -1; 
                   2976:     }
1.1112    www      2977:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2978:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2979: 	return -1;
                   2980:     }
1.1112    www      2981:     return $answer;
1.263     www      2982: }
                   2983: 
1.1111    www      2984: #
                   2985: # Return special version number of resource if set by override, empty otherwise
                   2986: #
                   2987: sub usedversion {
                   2988:     my $fname=shift;
                   2989:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2990:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2991:     if ($urlversion) { return $urlversion; }
                   2992:     return '';
                   2993: }
                   2994: 
1.1       albertel 2995: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2996: 
1.1       albertel 2997: sub subscribe {
                   2998:     my $fname=shift;
1.761     raeburn  2999:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3000:     $fname=~s/[\n\r]//g;
1.1       albertel 3001:     my $author=$fname;
                   3002:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3003:     my ($udom,$uname)=split(/\//,$author);
                   3004:     my $home=homeserver($uname,$udom);
1.335     albertel 3005:     if ($home eq 'no_host') {
                   3006:         return 'not_found';
1.1       albertel 3007:     }
                   3008:     my $answer=reply("sub:$fname",$home);
1.64      www      3009:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3010: 	$answer.=' by '.$home;
                   3011:     }
1.1       albertel 3012:     return $answer;
                   3013: }
                   3014:     
1.8       www      3015: # -------------------------------------------------------------- Replicate file
                   3016: 
                   3017: sub repcopy {
                   3018:     my $filename=shift;
1.23      www      3019:     $filename=~s/\/+/\//g;
1.1142    raeburn  3020:     my $londocroot = $perlvar{'lonDocRoot'};
                   3021:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3022:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3023:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3024: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3025: 	return &repcopy_userfile($filename);
                   3026:     }
1.532     albertel 3027:     $filename=~s/[\n\r]//g;
1.8       www      3028:     my $transname="$filename.in.transfer";
1.828     www      3029: # FIXME: this should flock
1.607     raeburn  3030:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3031:     my $remoteurl=subscribe($filename);
1.64      www      3032:     if ($remoteurl =~ /^con_lost by/) {
                   3033: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3034:            return 'unavailable';
1.8       www      3035:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3036: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3037: 	   return 'not_found';
1.64      www      3038:     } elsif ($remoteurl =~ /^rejected by/) {
                   3039: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3040:            return 'forbidden';
1.20      www      3041:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3042:            return 'ok';
1.8       www      3043:     } else {
1.290     www      3044:         my $author=$filename;
                   3045:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3046:         my ($udom,$uname)=split(/\//,$author);
                   3047:         my $home=homeserver($uname,$udom);
                   3048:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3049:            my @parts=split(/\//,$filename);
                   3050:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3051:            if ($path ne "$londocroot/res") {
1.8       www      3052:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3053: 	       return 'bad_request';
1.8       www      3054:            }
                   3055:            my $count;
                   3056:            for ($count=5;$count<$#parts;$count++) {
                   3057:                $path.="/$parts[$count]";
                   3058:                if ((-e $path)!=1) {
                   3059: 		   mkdir($path,0777);
                   3060:                }
                   3061:            }
                   3062:            my $ua=new LWP::UserAgent;
                   3063:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3064:            my $response=$ua->request($request,$transname);
                   3065:            if ($response->is_error()) {
                   3066: 	       unlink($transname);
                   3067:                my $message=$response->status_line;
1.672     albertel 3068:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3069:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3070:                return 'unavailable';
1.8       www      3071:            } else {
1.16      www      3072: 	       if ($remoteurl!~/\.meta$/) {
                   3073:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3074:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3075:                   if ($mresponse->is_error()) {
                   3076: 		      unlink($filename.'.meta');
                   3077:                       &logthis(
1.672     albertel 3078:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3079:                   }
                   3080: 	       }
1.8       www      3081:                rename($transname,$filename);
1.607     raeburn  3082:                return 'ok';
1.8       www      3083:            }
1.290     www      3084:        }
1.8       www      3085:     }
1.330     www      3086: }
                   3087: 
1.1172.2.124  raeburn  3088: # ------------------------------------------------- Unsubscribe from a resource
                   3089: 
                   3090: sub unsubscribe {
                   3091:     my ($fname) = @_;
                   3092:     my $answer;
                   3093:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3094:     $fname=~s/[\n\r]//g;
                   3095:     my $author=$fname;
                   3096:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3097:     my ($udom,$uname)=split(/\//,$author);
                   3098:     my $home=homeserver($uname,$udom);
                   3099:     if ($home eq 'no_host') {
                   3100:         $answer = 'no_host';
                   3101:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3102:         $answer = 'home';
                   3103:     } else {
1.1172.2.125  raeburn  3104:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3105:     }
                   3106:     return $answer;
                   3107: }
                   3108: 
1.330     www      3109: # ------------------------------------------------ Get server side include body
                   3110: sub ssi_body {
1.381     albertel 3111:     my ($filelink,%form)=@_;
1.606     matthew  3112:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3113:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3114:     }
1.953     www      3115:     my $output='';
                   3116:     my $response;
1.980     raeburn  3117:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3118:        ($output,$response)=&externalssi($filelink);
1.953     www      3119:     } else {
1.1004    droeschl 3120:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3121:        $filelink .= 'inhibitmenu=yes';
1.953     www      3122:        ($output,$response)=&ssi($filelink,%form);
                   3123:     }
1.778     albertel 3124:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3125:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3126:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3127:     if (wantarray) {
                   3128:         return ($output, $response);
                   3129:     } else {
                   3130:         return $output;
                   3131:     }
1.8       www      3132: }
                   3133: 
1.15      www      3134: # --------------------------------------------------------- Server Side Include
                   3135: 
1.782     albertel 3136: sub absolute_url {
                   3137:     my ($host_name) = @_;
                   3138:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3139:     if ($host_name eq '') {
                   3140: 	$host_name = $ENV{'SERVER_NAME'};
                   3141:     }
                   3142:     return $protocol.$host_name;
                   3143: }
                   3144: 
1.942     foxr     3145: #
                   3146: #   Server side include.
                   3147: # Parameters:
                   3148: #  fn     Possibly encrypted resource name/id.
                   3149: #  form   Hash that describes how the rendering should be done
                   3150: #         and other things.
1.944     foxr     3151: # Returns:
1.950     raeburn  3152: #   Scalar context: The content of the response.
                   3153: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3154: #     
1.15      www      3155: sub ssi {
                   3156: 
1.944     foxr     3157:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3158:     my ($request,$response);
1.711     albertel 3159: 
                   3160:     $form{'no_update_last_known'}=1;
1.895     albertel 3161:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3162:     if (%form) {
1.782     albertel 3163:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3164:       $request->content(join('&',map {
                   3165:             my $name = escape($_);
                   3166:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3167:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3168:             : &escape($form{$_}) );
                   3169:         } keys(%form)));
1.23      www      3170:     } else {
1.782     albertel 3171:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3172:     }
                   3173: 
1.15      www      3174:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3175: 
1.1172.2.101  raeburn  3176:     if (($env{'request.course.id'}) &&
                   3177:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3178:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3179:         ($form{'grade_symb'} ne '') &&
                   3180:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3181:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3182:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3183:             my $ua=new LWP::UserAgent;
                   3184:             $ua->local_address('127.0.0.1');
                   3185:             $response = $ua->request($request);
                   3186:         } else {
                   3187:             {
                   3188:                 require LWP::Protocol::http;
                   3189:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3190:                 my $ua=new LWP::UserAgent;
                   3191:                 $response = $ua->request($request);
                   3192:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3193:             }
                   3194:         }
                   3195:     } else {
                   3196:         my $ua=new LWP::UserAgent;
                   3197:         $response = $ua->request($request);
                   3198:     }
1.944     foxr     3199:     if (wantarray) {
1.1172.2.3  raeburn  3200: 	return ($response->content, $response);
1.944     foxr     3201:     } else {
1.1172.2.3  raeburn  3202: 	return $response->content;
1.942     foxr     3203:     }
1.324     www      3204: }
                   3205: 
                   3206: sub externalssi {
                   3207:     my ($url)=@_;
                   3208:     my $ua=new LWP::UserAgent;
                   3209:     my $request=new HTTP::Request('GET',$url);
                   3210:     my $response=$ua->request($request);
1.954     raeburn  3211:     if (wantarray) {
                   3212:         return ($response->content, $response);
                   3213:     } else {
                   3214:         return $response->content;
                   3215:     }
1.15      www      3216: }
1.254     www      3217: 
1.1172.2.98  raeburn  3218: # If the local copy of a replicated resource is outdated, trigger a
                   3219: # connection from the homeserver to flush the delayed queue. If no update
                   3220: # happens, remove local copies of outdated resource (and corresponding
                   3221: # metadata file).
                   3222: 
                   3223: sub remove_stale_resfile {
                   3224:     my ($url) = @_;
                   3225:     my $removed;
                   3226:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3227:         my $audom = $1;
                   3228:         my $auname = $2;
                   3229:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3230:             my $homeserver = &homeserver($auname,$audom);
                   3231:             unless (($homeserver eq 'no_host') ||
                   3232:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3233:                 my $fname = &filelocation('',$url);
                   3234:                 if (-e $fname) {
                   3235:                     my $hostname = &hostname($homeserver);
                   3236:                     if ($hostname) {
1.1172.2.120  raeburn  3237:                         my $protocol = $protocol{$homeserver};
                   3238:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3239:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3240:                         my $ua=new LWP::UserAgent;
                   3241:                         $ua->timeout(5);
1.1172.2.98  raeburn  3242:                         my $request=new HTTP::Request('HEAD',$uri);
                   3243:                         my $response=$ua->request($request);
                   3244:                         if ($response->is_success()) {
                   3245:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3246:                             my $locmodtime = (stat($fname))[9];
                   3247:                             if ($locmodtime < $remmodtime) {
                   3248:                                 my $stale;
                   3249:                                 my $answer = &reply('pong',$homeserver);
                   3250:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3251:                                     sleep(0.2);
                   3252:                                     $locmodtime = (stat($fname))[9];
                   3253:                                     if ($locmodtime < $remmodtime) {
                   3254:                                         my $posstransfer = $fname.'.in.transfer';
                   3255:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3256:                                             $removed = 1;
                   3257:                                         } else {
                   3258:                                             $stale = 1;
                   3259:                                         }
                   3260:                                     } else {
                   3261:                                         $removed = 1;
                   3262:                                     }
                   3263:                                 } else {
                   3264:                                     $stale = 1;
                   3265:                                 }
                   3266:                                 if ($stale) {
1.1172.2.124  raeburn  3267:                                     if (unlink($fname)) {
                   3268:                                         if ($uri!~/\.meta$/) {
                   3269:                                             if (-e $fname.'.meta') {
                   3270:                                                 unlink($fname.'.meta');
                   3271:                                             }
                   3272:                                         }
                   3273:                                         my $unsubresult = &unsubscribe($fname);
                   3274:                                         unless ($unsubresult eq 'ok') {
                   3275:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3276:                                         }
                   3277:                                         $removed = 1;
1.1172.2.98  raeburn  3278:                                     }
                   3279:                                 }
                   3280:                             }
                   3281:                         }
                   3282:                     }
                   3283:                 }
                   3284:             }
                   3285:         }
                   3286:     }
                   3287:     return $removed;
                   3288: }
                   3289: 
1.492     albertel 3290: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3291: 
                   3292: sub allowuploaded {
                   3293:     my ($srcurl,$url)=@_;
                   3294:     $url=&clutter(&declutter($url));
                   3295:     my $dir=$url;
                   3296:     $dir=~s/\/[^\/]+$//;
                   3297:     my %httpref=();
                   3298:     my $httpurl=&hreflocation('',$url);
                   3299:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3300:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3301: }
1.477     raeburn  3302: 
1.1172.2.13  raeburn  3303: #
                   3304: # Determine if the current user should be able to edit a particular resource,
                   3305: # when viewing in course context.
                   3306: # (a) When viewing resource used to determine if "Edit" item is included in
                   3307: #     Functions.
                   3308: # (b) When displaying folder contents in course editor, used to determine if
                   3309: #     "Edit" link will be displayed alongside resource.
                   3310: #
                   3311: #  input: six args -- filename (decluttered), course number, course domain,
                   3312: #                   url, symb (if registered) and group (if this is a group
                   3313: #                   item -- e.g., bulletin board, group page etc.).
                   3314: #  output: array of five scalars --
                   3315: #          $cfile -- url for file editing if editable on current server
                   3316: #          $home -- homeserver of resource (i.e., for author if published,
                   3317: #                                           or course if uploaded.).
                   3318: #          $switchserver --  1 if server switch will be needed.
                   3319: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3320: #          $forceview -- 1 if icon/link should be to go to view mode
                   3321: #
                   3322: 
                   3323: sub can_edit_resource {
                   3324:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3325:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3326: #
                   3327: # For aboutme pages user can only edit his/her own.
                   3328: #
                   3329:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3330:         my ($sdom,$sname) = ($1,$2);
                   3331:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3332:             $home = $env{'user.home'};
                   3333:             $cfile = $resurl;
                   3334:             if ($env{'form.forceedit'}) {
                   3335:                 $forceview = 1;
                   3336:             } else {
                   3337:                 $forceedit = 1;
                   3338:             }
                   3339:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3340:         } else {
                   3341:             return;
                   3342:         }
                   3343:     }
                   3344: 
                   3345:     if ($env{'request.course.id'}) {
                   3346:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3347:         if ($group ne '') {
                   3348: # if this is a group homepage or group bulletin board, check group privs
                   3349:             my $allowed = 0;
                   3350:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3351:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3352:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3353:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3354:                     $allowed = 1;
                   3355:                 }
                   3356:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3357:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3358:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3359:                     $allowed = 1;
                   3360:                 }
                   3361:             }
                   3362:             if ($allowed) {
                   3363:                 $home=&homeserver($cnum,$cdom);
                   3364:                 if ($env{'form.forceedit'}) {
                   3365:                     $forceview = 1;
                   3366:                 } else {
                   3367:                     $forceedit = 1;
                   3368:                 }
                   3369:                 $cfile = $resurl;
                   3370:             } else {
                   3371:                 return;
                   3372:             }
                   3373:         } else {
1.1172.2.15  raeburn  3374:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3375:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3376:                     return;
                   3377:                 }
                   3378:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3379: #
                   3380: # No edit allowed where CC has switched to student role.
                   3381: #
                   3382:                 return;
                   3383:             }
                   3384:         }
                   3385:     }
                   3386: 
                   3387:     if ($file ne '') {
                   3388:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3389:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3390:                 $uploaded = 1;
                   3391:                 $incourse = 1;
                   3392:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3393:                     $cfile = &hreflocation('',$file);
                   3394:                     if ($env{'form.forceedit'}) {
                   3395:                         $forceview = 1;
                   3396:                     } else {
                   3397:                         $forceedit = 1;
                   3398:                     }
                   3399:                 }
                   3400:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3401:                 $incourse = 1;
                   3402:                 if ($env{'form.forceedit'}) {
                   3403:                     $forceview = 1;
                   3404:                 } else {
                   3405:                     $forceedit = 1;
                   3406:                 }
                   3407:                 $cfile = $resurl;
                   3408:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3409:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3410:                     $incourse = 1;
                   3411:                     if ($env{'form.forceedit'}) {
                   3412:                         $forceview = 1;
                   3413:                     } else {
                   3414:                         $forceedit = 1;
                   3415:                     }
                   3416:                     $cfile = $resurl;
                   3417:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3418:                     $incourse = 1;
                   3419:                     $cfile = $resurl.'/smpedit';
                   3420:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3421:                     $incourse = 1;
                   3422:                     if ($env{'form.forceedit'}) {
                   3423:                         $forceview = 1;
                   3424:                     } else {
                   3425:                         $forceedit = 1;
                   3426:                     }
                   3427:                     $cfile = $resurl;
1.1172.2.122  raeburn  3428:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3429:                     my ($map,$id,$res) = &decode_symb($symb);
                   3430:                     if ($map =~ /\.page$/) {
                   3431:                         $incourse = 1;
                   3432:                         if ($env{'form.forceedit'}) {
                   3433:                             $forceview = 1;
                   3434:                             $cfile = $map;
                   3435:                         } else {
                   3436:                             $forceedit = 1;
                   3437:                             $cfile =  '/adm/wrapper'.$resurl;
                   3438:                         }
                   3439:                     }
1.1172.2.15  raeburn  3440:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3441:                     $incourse = 1;
                   3442:                     if ($env{'form.forceedit'}) {
                   3443:                         $forceview = 1;
                   3444:                     } else {
                   3445:                         $forceedit = 1;
                   3446:                     }
                   3447:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3448:                 }
                   3449:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3450:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3451:                 if (&is_on_map($template)) {
                   3452:                     $incourse = 1;
                   3453:                     $forceview = 1;
                   3454:                     $cfile = $template;
                   3455:                 }
                   3456:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3457:                 $incourse = 1;
                   3458:                 if ($env{'form.forceedit'}) {
                   3459:                     $forceview = 1;
                   3460:                 } else {
                   3461:                     $forceedit = 1;
                   3462:                 }
                   3463:                 $cfile = $resurl;
1.1172.2.13  raeburn  3464:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3465:                 $incourse = 1;
                   3466:                 $forceview = 1;
                   3467:                 if ($symb) {
                   3468:                     my ($map,$id,$res)=&decode_symb($symb);
                   3469:                     $env{'request.symb'} = $symb;
                   3470:                     $cfile = &clutter($res);
                   3471:                 } else {
                   3472:                     $cfile = $env{'form.suppurl'};
                   3473:                     $cfile =~ s{^http://}{};
                   3474:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3475:                 }
1.1172.2.31  raeburn  3476:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3477:                 if ($env{'form.forceedit'}) {
                   3478:                     $forceview = 1;
                   3479:                 } else {
                   3480:                     $forceedit = 1;
                   3481:                 }
                   3482:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3483:             }
                   3484:         }
                   3485:         if ($uploaded || $incourse) {
                   3486:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3487:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3488:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3489:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3490:             # Check that the user has permission to edit this resource
                   3491:             my $setpriv = 1;
                   3492:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3493:             if (defined($cfudom)) {
                   3494:                 $home=&homeserver($cfuname,$cfudom);
                   3495:                 $cfile=$file;
                   3496:             }
                   3497:         }
                   3498:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3499:             (($home ne '') && ($home ne 'no_host'))) {
                   3500:             my @ids=&current_machine_ids();
                   3501:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3502:                 $switchserver=1;
                   3503:             }
                   3504:         }
                   3505:     }
                   3506:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3507: }
                   3508: 
                   3509: sub is_course_upload {
                   3510:     my ($file,$cnum,$cdom) = @_;
                   3511:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3512:     $uploadpath =~ s{^\/}{};
                   3513:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3514:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3515:         return 1;
                   3516:     }
                   3517:     return;
                   3518: }
                   3519: 
                   3520: sub in_course {
                   3521:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3522:     if ($hideprivileged) {
                   3523:         my $skipuser;
1.1172.2.23  raeburn  3524:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3525:         my @possdoms = ($cdom);
                   3526:         if ($coursehash{'checkforpriv'}) {
                   3527:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3528:         }
                   3529:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3530:             $skipuser = 1;
                   3531:             if ($coursehash{'nothideprivileged'}) {
                   3532:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3533:                     my $user;
                   3534:                     if ($item =~ /:/) {
                   3535:                         $user = $item;
                   3536:                     } else {
                   3537:                         $user = join(':',split(/[\@]/,$item));
                   3538:                     }
                   3539:                     if ($user eq $uname.':'.$udom) {
                   3540:                         undef($skipuser);
                   3541:                         last;
                   3542:                     }
                   3543:                 }
                   3544:             }
                   3545:             if ($skipuser) {
                   3546:                 return 0;
                   3547:             }
                   3548:         }
                   3549:     }
                   3550:     $type ||= 'any';
                   3551:     if (!defined($cdom) || !defined($cnum)) {
                   3552:         my $cid  = $env{'request.course.id'};
                   3553:         $cdom = $env{'course.'.$cid.'.domain'};
                   3554:         $cnum = $env{'course.'.$cid.'.num'};
                   3555:     }
                   3556:     my $typesref;
                   3557:     if (($type eq 'any') || ($type eq 'all')) {
                   3558:         $typesref = ['active','previous','future'];
                   3559:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3560:         $typesref = [$type];
                   3561:     }
                   3562:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3563:                               $typesref,undef,[$cdom]);
                   3564:     my ($tmp) = keys(%roles);
                   3565:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3566:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3567:     if (@course_roles > 0) {
                   3568:         return 1;
                   3569:     }
                   3570:     return 0;
                   3571: }
                   3572: 
1.478     albertel 3573: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3574: # input: action, courseID, current domain, intended
1.637     raeburn  3575: #        path to file, source of file, instruction to parse file for objects,
                   3576: #        ref to hash for embedded objects,
                   3577: #        ref to hash for codebase of java objects.
1.1095    raeburn  3578: #        reference to scalar to accommodate mime type determined
                   3579: #          from File::MMagic if $parser = parse.
1.637     raeburn  3580: #
1.485     raeburn  3581: # output: url to file (if action was uploaddoc), 
                   3582: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3583: #
1.478     albertel 3584: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3585: # course.
1.477     raeburn  3586: #
1.478     albertel 3587: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3588: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3589: #          course's home server.
1.477     raeburn  3590: #
1.478     albertel 3591: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3592: #          be copied from $source (current location) to 
                   3593: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3594: #         and will then be copied to
                   3595: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3596: #         course's home server.
1.485     raeburn  3597: #
1.481     raeburn  3598: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3599: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3600: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3601: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3602: #         in course's home server.
1.637     raeburn  3603: #
1.477     raeburn  3604: 
                   3605: sub process_coursefile {
1.1095    raeburn  3606:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3607:         $mimetype)=@_;
1.477     raeburn  3608:     my $fetchresult;
1.638     albertel 3609:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3610:     if ($action eq 'propagate') {
1.638     albertel 3611:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3612: 			     $home);
1.481     raeburn  3613:     } else {
1.477     raeburn  3614:         my $fpath = '';
                   3615:         my $fname = $file;
1.478     albertel 3616:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3617:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3618:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3619:         if ($action eq 'copy') {
                   3620:             if ($source eq '') {
                   3621:                 $fetchresult = 'no source file';
                   3622:                 return $fetchresult;
                   3623:             } else {
                   3624:                 my $destination = $filepath.'/'.$fname;
                   3625:                 rename($source,$destination);
                   3626:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3627:                                  $home);
1.481     raeburn  3628:             }
                   3629:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3630:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3631:             print $fh $env{'form.'.$source};
1.481     raeburn  3632:             close($fh);
1.637     raeburn  3633:             if ($parser eq 'parse') {
1.1024    raeburn  3634:                 my $mm = new File::MMagic;
1.1095    raeburn  3635:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3636:                 if ($type eq 'text/html') {
1.1024    raeburn  3637:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3638:                     unless ($parse_result eq 'ok') {
                   3639:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3640:                     }
1.637     raeburn  3641:                 }
1.1095    raeburn  3642:                 if (ref($mimetype)) {
                   3643:                     $$mimetype = $type;
                   3644:                 } 
1.637     raeburn  3645:             }
1.477     raeburn  3646:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3647:                                  $home);
1.481     raeburn  3648:             if ($fetchresult eq 'ok') {
                   3649:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3650:             } else {
                   3651:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3652:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3653:                 return '/adm/notfound.html';
                   3654:             }
1.477     raeburn  3655:         }
                   3656:     }
1.485     raeburn  3657:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3658:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3659:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3660:     }
                   3661:     return $fetchresult;
                   3662: }
                   3663: 
1.637     raeburn  3664: sub build_filepath {
                   3665:     my ($fpath) = @_;
                   3666:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3667:     unless ($fpath eq '') {
                   3668:         my @parts=split('/',$fpath);
                   3669:         foreach my $part (@parts) {
                   3670:             $filepath.= '/'.$part;
                   3671:             if ((-e $filepath)!=1) {
                   3672:                 mkdir($filepath,0777);
                   3673:             }
                   3674:         }
                   3675:     }
                   3676:     return $filepath;
                   3677: }
                   3678: 
                   3679: sub store_edited_file {
1.638     albertel 3680:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3681:     my $file = $primary_url;
                   3682:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3683:     my $fpath = '';
                   3684:     my $fname = $file;
                   3685:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3686:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3687:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3688:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3689:     print $fh $content;
                   3690:     close($fh);
1.638     albertel 3691:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3692:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3693: 			  $home);
1.637     raeburn  3694:     if ($$fetchresult eq 'ok') {
                   3695:         return '/uploaded/'.$fpath.'/'.$fname;
                   3696:     } else {
1.638     albertel 3697:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3698: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3699:         return '/adm/notfound.html';
                   3700:     }
                   3701: }
                   3702: 
1.531     albertel 3703: sub clean_filename {
1.831     albertel 3704:     my ($fname,$args)=@_;
1.315     www      3705: # Replace Windows backslashes by forward slashes
1.257     www      3706:     $fname=~s/\\/\//g;
1.831     albertel 3707:     if (!$args->{'keep_path'}) {
                   3708:         # Get rid of everything but the actual filename
                   3709: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3710:     }
1.315     www      3711: # Replace spaces by underscores
                   3712:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3713: # Transliterate non-ascii text to ascii
                   3714:     my $lang = &Apache::lonlocal::current_language();
                   3715:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3716: # Replace all other weird characters by nothing
1.831     albertel 3717:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3718: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3719: # numbers
                   3720:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3721:     return $fname;
                   3722: }
1.1172.2.110  raeburn  3723: 
1.1051    raeburn  3724: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3725: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3726: # image with the same aspect ratio as the original, but with dimensions which do 
                   3727: # not exceed $resizewidth and $resizeheight.
                   3728:  
1.984     neumanie 3729: sub resizeImage {
1.1051    raeburn  3730:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3731:     my $ima = Image::Magick->new;
                   3732:     my $resized;
                   3733:     if (-e $img_path) {
                   3734:         $ima->Read($img_path);
                   3735:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3736:             my $width = $ima->Get('width');
                   3737:             my $height = $ima->Get('height');
                   3738:             if ($width > $resizewidth) {
                   3739: 	        my $factor = $width/$resizewidth;
                   3740:                 my $newheight = $height/$factor;
                   3741:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3742:                 $resized = 1;
                   3743:             }
                   3744:         }
                   3745:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3746:             my $width = $ima->Get('width');
                   3747:             my $height = $ima->Get('height');
                   3748:             if ($height > $resizeheight) {
                   3749:                 my $factor = $height/$resizeheight;
                   3750:                 my $newwidth = $width/$factor;
                   3751:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3752:                 $resized = 1;
                   3753:             }
                   3754:         }
                   3755:         if ($resized) {
                   3756:             $ima->Write($img_path);
                   3757:         }
                   3758:     }
                   3759:     return;
1.977     amueller 3760: }
                   3761: 
1.608     albertel 3762: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3763: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3764: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3765: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3766: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3767: #                   if 'coursedoc': upload to the current course
                   3768: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3769: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3770: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3771: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3772: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3773: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3774: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3775: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3776: #        $allfiles - reference to hash for embedded objects
                   3777: #        $codebase - reference to hash for codebase of java objects
                   3778: #        $desuname - username for permanent storage of uploaded file
                   3779: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3780: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3781: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3782: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3783: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3784: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3785: #                    from File::MMagic.
1.858     raeburn  3786: # 
1.686     albertel 3787: # output: url of file in userspace, or error: <message> 
                   3788: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3789: 
1.531     albertel 3790: sub userfileupload {
1.1090    raeburn  3791:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3792:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3793:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3794:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3795:     $fname=&clean_filename($fname);
1.1090    raeburn  3796:     # See if there is anything left
1.257     www      3797:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3798:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3799:     if ($fname =~ /^\./) {
                   3800:         my ($s,$usec) = &gettimeofday();
                   3801:         while (length($usec) < 6) {
                   3802:             $usec = '0'.$usec;
                   3803:         }
                   3804:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3805:     }
1.1090    raeburn  3806:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3807:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3808:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3809:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3810:         my $now = time;
1.1090    raeburn  3811:         my $filepath;
1.1095    raeburn  3812:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3813:              $filepath = 'tmp/helprequests/'.$now;
                   3814:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3815:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3816:                          '_'.$env{'user.domain'}.'/pending';
                   3817:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3818:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3819:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3820:                 $docudom = $destudom;
                   3821:             } else {
                   3822:                 $docudom = $env{'user.domain'};
                   3823:             }
1.1172.2.96  raeburn  3824:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3825:                 $docuname = $destuname;
                   3826:             } else {
                   3827:                 $docuname = $env{'user.name'};
                   3828:             }
                   3829:             if (exists($env{'form.group'})) {
                   3830:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3831:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3832:             }
                   3833:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3834:             if ($context eq 'canceloverwrite') {
                   3835:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3836:                 if (-e  $tempfile) {
                   3837:                     my @info = stat($tempfile);
                   3838:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3839:                         unlink($tempfile);
                   3840:                     }
                   3841:                 }
                   3842:                 return;
1.523     raeburn  3843:             }
                   3844:         }
1.1090    raeburn  3845:         # Create the directory if not present
1.741     raeburn  3846:         my @parts=split(/\//,$filepath);
                   3847:         my $fullpath = $perlvar{'lonDaemons'};
                   3848:         for (my $i=0;$i<@parts;$i++) {
                   3849:             $fullpath .= '/'.$parts[$i];
                   3850:             if ((-e $fullpath)!=1) {
                   3851:                 mkdir($fullpath,0777);
                   3852:             }
                   3853:         }
1.1172.2.96  raeburn  3854:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3855:         print $fh $env{'form.'.$formname};
                   3856:         close($fh);
1.1090    raeburn  3857:         if ($context eq 'existingfile') {
                   3858:             my @info = stat($fullpath.'/'.$fname);
                   3859:             return ($fullpath.'/'.$fname,$info[9]);
                   3860:         } else {
                   3861:             return $fullpath.'/'.$fname;
                   3862:         }
1.523     raeburn  3863:     }
1.995     raeburn  3864:     if ($subdir eq 'scantron') {
                   3865:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3866:     } else {
1.995     raeburn  3867:         $fname="$subdir/$fname";
                   3868:     }
1.1090    raeburn  3869:     if ($context eq 'coursedoc') {
1.638     albertel 3870: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3871: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3872:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3873:             return &finishuserfileupload($docuname,$docudom,
                   3874: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3875: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3876:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3877:         } else {
1.1172.2.21  raeburn  3878:             if ($env{'form.folder'}) {
                   3879:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3880:             }
1.638     albertel 3881:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3882: 				       $fname,$formname,$parser,
1.1095    raeburn  3883: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3884:         }
1.719     banghart 3885:     } elsif (defined($destuname)) {
                   3886:         my $docuname=$destuname;
                   3887:         my $docudom=$destudom;
1.860     raeburn  3888: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3889: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3890:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3891:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3892:     } else {
1.638     albertel 3893:         my $docuname=$env{'user.name'};
                   3894:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3895:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3896:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3897:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3898:         }
1.860     raeburn  3899: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3900: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3901:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3902:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3903:     }
1.271     www      3904: }
                   3905: 
                   3906: sub finishuserfileupload {
1.860     raeburn  3907:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3908:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3909:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3910:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3911:   
1.860     raeburn  3912:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3913:     $file=$fname;
                   3914:     if ($fname=~m|/|) {
                   3915:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3916: 	$path.=$fnamepath.'/';
                   3917:     }
1.259     www      3918:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3919:     my $count;
                   3920:     for ($count=4;$count<=$#parts;$count++) {
                   3921:         $filepath.="/$parts[$count]";
                   3922:         if ((-e $filepath)!=1) {
                   3923: 	    mkdir($filepath,0777);
                   3924:         }
                   3925:     }
1.984     neumanie 3926: 
1.258     www      3927: # Save the file
                   3928:     {
1.1172.2.96  raeburn  3929: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3930: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3931: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3932: 	    return '/adm/notfound.html';
                   3933: 	}
1.1090    raeburn  3934:         if ($context eq 'overwrite') {
1.1117    foxr     3935:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3936:             my $target = $filepath.'/'.$file;
                   3937:             if (-e $source) {
                   3938:                 my @info = stat($source);
                   3939:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3940:                     unless (&File::Copy::move($source,$target)) {
                   3941:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3942:                         return "Moving from $source failed";
                   3943:                     }
                   3944:                 } else {
                   3945:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3946:                 }
                   3947:             } else {
                   3948:                 return "Temporary file: $source missing";
                   3949:             }
                   3950:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3951: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3952: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3953: 	    return '/adm/notfound.html';
                   3954: 	}
1.570     albertel 3955: 	close(FH);
1.1051    raeburn  3956:         if ($resizewidth && $resizeheight) {
                   3957:             my $mm = new File::MMagic;
                   3958:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3959:             if ($mime_type =~ m{^image/}) {
                   3960: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3961:             }  
1.977     amueller 3962: 	}
1.258     www      3963:     }
1.1152    raeburn  3964:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3965:         if (ref($mimetype)) {
                   3966:             if ($$mimetype eq '') {
                   3967:                 my $mm = new File::MMagic;
                   3968:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3969:                 $$mimetype = $type;
                   3970:             }
                   3971:         }
                   3972:     }
1.1172.2.109  raeburn  3973:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3974:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3975:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3976:                                                        $allfiles,$codebase);
                   3977:             unless ($parse_result eq 'ok') {
                   3978:                 &logthis('Failed to parse '.$filepath.$file.
                   3979: 	   	         ' for embedded media: '.$parse_result); 
                   3980:             }
1.637     raeburn  3981:         }
1.1172.2.109  raeburn  3982:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3983:         my $format = $env{'form.scantron_format'};
                   3984:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3985:     }
1.860     raeburn  3986:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3987:         my $input = $filepath.'/'.$file;
                   3988:         my $output = $filepath.'/'.'tn-'.$file;
                   3989:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3990:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3991:         system({$args[0]} @args);
1.860     raeburn  3992:         if (-e $filepath.'/'.'tn-'.$file) {
                   3993:             $fetchthumb  = 1; 
                   3994:         }
                   3995:     }
1.858     raeburn  3996:  
1.259     www      3997: # Notify homeserver to grep it
                   3998: #
1.984     neumanie 3999:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4000:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4001:     if ($fetchresult eq 'ok') {
1.860     raeburn  4002:         if ($fetchthumb) {
                   4003:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4004:             if ($thumbresult ne 'ok') {
                   4005:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4006:                          $docuhome.': '.$thumbresult);
                   4007:             }
                   4008:         }
1.259     www      4009: #
1.258     www      4010: # Return the URL to it
1.494     albertel 4011:         return '/uploaded/'.$path.$file;
1.263     www      4012:     } else {
1.494     albertel 4013:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4014: 		 ': '.$fetchresult);
1.263     www      4015:         return '/adm/notfound.html';
1.858     raeburn  4016:     }
1.493     albertel 4017: }
                   4018: 
1.637     raeburn  4019: sub extract_embedded_items {
1.961     raeburn  4020:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4021:     my @state = ();
1.1164    raeburn  4022:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4023:     my %javafiles = (
                   4024:                       codebase => '',
                   4025:                       code => '',
                   4026:                       archive => ''
                   4027:                     );
                   4028:     my %mediafiles = (
                   4029:                       src => '',
                   4030:                       movie => '',
                   4031:                      );
1.648     raeburn  4032:     my $p;
                   4033:     if ($content) {
                   4034:         $p = HTML::LCParser->new($content);
                   4035:     } else {
1.961     raeburn  4036:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4037:     }
1.641     albertel 4038:     while (my $t=$p->get_token()) {
1.640     albertel 4039: 	if ($t->[0] eq 'S') {
                   4040: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4041: 	    push(@state, $tagname);
1.648     raeburn  4042:             if (lc($tagname) eq 'allow') {
                   4043:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4044:             }
1.640     albertel 4045: 	    if (lc($tagname) eq 'img') {
                   4046: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4047: 	    }
1.886     albertel 4048: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4049:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4050: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4051:                 }
1.886     albertel 4052: 	    }
1.645     raeburn  4053:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4054:                 my $src;
1.645     raeburn  4055:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4056:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4057:                 } else {
1.1164    raeburn  4058:                     if ($attr->{'src'} ne '') {
                   4059:                         $src = $attr->{'src'};
                   4060:                         &add_filetype($allfiles,$src,'src');
                   4061:                     }
                   4062:                 }
                   4063:                 my $text = $p->get_trimmed_text();
                   4064:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4065:                     my @swfargs = split(/,/,$1);
                   4066:                     foreach my $item (@swfargs) {
                   4067:                         $item =~ s/["']//g;
                   4068:                         $item =~ s/^\s+//;
                   4069:                         $item =~ s/\s+$//;
                   4070:                     }
                   4071:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4072:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4073:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4074:                         } else {
                   4075:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4076:                         }
                   4077:                     }
1.645     raeburn  4078:                 }
                   4079:             }
                   4080:             if (lc($tagname) eq 'link') {
                   4081:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4082:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4083:                 }
                   4084:             }
1.640     albertel 4085: 	    if (lc($tagname) eq 'object' ||
                   4086: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4087: 		foreach my $item (keys(%javafiles)) {
                   4088: 		    $javafiles{$item} = '';
                   4089: 		}
1.1164    raeburn  4090:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4091:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4092:                 }
1.640     albertel 4093: 	    }
                   4094: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4095: 		my $name = lc($attr->{'name'});
                   4096: 		foreach my $item (keys(%javafiles)) {
                   4097: 		    if ($name eq $item) {
                   4098: 			$javafiles{$item} = $attr->{'value'};
                   4099: 			last;
                   4100: 		    }
                   4101: 		}
1.1164    raeburn  4102:                 my $pathfrom;
1.640     albertel 4103: 		foreach my $item (keys(%mediafiles)) {
                   4104: 		    if ($name eq $item) {
1.1164    raeburn  4105:                         $pathfrom = $attr->{'value'};
                   4106:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4107: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4108: 			last;
                   4109: 		    }
                   4110: 		}
1.1164    raeburn  4111:                 if ($name eq 'flashvars') {
                   4112:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4113:                 }
                   4114:                 if ($pathfrom ne '') {
                   4115:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4116:                                          $pathfrom);
                   4117:                 }
1.640     albertel 4118: 	    }
                   4119: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4120: 		foreach my $item (keys(%javafiles)) {
                   4121: 		    if ($attr->{$item}) {
                   4122: 			$javafiles{$item} = $attr->{$item};
                   4123: 			last;
                   4124: 		    }
                   4125: 		}
                   4126: 		foreach my $item (keys(%mediafiles)) {
                   4127: 		    if ($attr->{$item}) {
                   4128: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4129: 			last;
                   4130: 		    }
                   4131: 		}
1.1164    raeburn  4132:                 if (lc($tagname) eq 'embed') {
                   4133:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4134:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4135:                                              $attr->{'src'});
                   4136:                     }
                   4137:                 }
1.640     albertel 4138: 	    }
1.1172.2.35  raeburn  4139:             if (lc($tagname) eq 'iframe') {
                   4140:                 my $src = $attr->{'src'} ;
                   4141:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4142:                     &add_filetype($allfiles,$src,'src');
                   4143:                 } elsif ($src =~ m{^/}) {
                   4144:                     if ($env{'request.course.id'}) {
                   4145:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4146:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4147:                         my $url = &hreflocation('',$fullpath);
                   4148:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4149:                             my $relpath = $1;
                   4150:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4151:                                 &add_filetype($allfiles,$1,'src');
                   4152:                             }
                   4153:                         }
                   4154:                     }
                   4155:                 }
                   4156:             }
1.1164    raeburn  4157:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4158:                 pop(@state);
1.1164    raeburn  4159:             }
1.640     albertel 4160: 	} elsif ($t->[0] eq 'E') {
                   4161: 	    my ($tagname) = ($t->[1]);
                   4162: 	    if ($javafiles{'codebase'} ne '') {
                   4163: 		$javafiles{'codebase'} .= '/';
                   4164: 	    }  
                   4165: 	    if (lc($tagname) eq 'applet' ||
                   4166: 		lc($tagname) eq 'object' ||
                   4167: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4168: 		) {
                   4169: 		foreach my $item (keys(%javafiles)) {
                   4170: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4171: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4172: 			&add_filetype($allfiles,$file,$item);
                   4173: 		    }
                   4174: 		}
                   4175: 	    } 
                   4176: 	    pop @state;
                   4177: 	}
                   4178:     }
1.1164    raeburn  4179:     foreach my $id (sort(keys(%flashvars))) {
                   4180:         if ($shockwave{$id} ne '') {
                   4181:             my @pairs = split(/\&/,$flashvars{$id});
                   4182:             foreach my $pair (@pairs) {
                   4183:                 my ($key,$value) = split(/\=/,$pair);
                   4184:                 if ($key eq 'thumb') {
                   4185:                     &add_filetype($allfiles,$value,$key);
                   4186:                 } elsif ($key eq 'content') {
                   4187:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4188:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4189:                     if ($ext ne '') {
                   4190:                         &add_filetype($allfiles,$path.$value,$ext);
                   4191:                     }
                   4192:                 }
                   4193:             }
                   4194:         }
                   4195:     }
1.637     raeburn  4196:     return 'ok';
                   4197: }
                   4198: 
1.639     albertel 4199: sub add_filetype {
                   4200:     my ($allfiles,$file,$type)=@_;
                   4201:     if (exists($allfiles->{$file})) {
                   4202: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4203: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4204: 	}
                   4205:     } else {
                   4206: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4207:     }
                   4208: }
                   4209: 
1.1164    raeburn  4210: sub embedded_dependency {
                   4211:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4212:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4213:         if (($identifier ne '') &&
                   4214:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4215:             ($pathfrom ne '')) {
                   4216:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4217:             foreach my $dep (@{$related->{$identifier}}) {
                   4218:                 &add_filetype($allfiles,$path.$dep,'object');
                   4219:             }
                   4220:         }
                   4221:     }
                   4222:     return;
                   4223: }
                   4224: 
1.1172.2.109  raeburn  4225: sub bubblesheet_converter {
                   4226:     my ($cdom,$fullpath,$config,$format) = @_;
                   4227:     if ((&domain($cdom) ne '') &&
                   4228:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4229:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4230:         my (%csvcols,%csvoptions);
                   4231:         if (ref($config->{'fields'}) eq 'HASH') {
                   4232:             %csvcols = %{$config->{'fields'}};
                   4233:         }
                   4234:         if (ref($config->{'options'}) eq 'HASH') {
                   4235:             %csvoptions = %{$config->{'options'}};
                   4236:         }
                   4237:         my %csvbynum = reverse(%csvcols);
                   4238:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4239:         if (keys(%scantronconf)) {
                   4240:             my %bynum = (
                   4241:                           $scantronconf{CODEstart} => 'CODEstart',
                   4242:                           $scantronconf{IDstart}   => 'IDstart',
                   4243:                           $scantronconf{PaperID}   => 'PaperID',
                   4244:                           $scantronconf{FirstName} => 'FirstName',
                   4245:                           $scantronconf{LastName}  => 'LastName',
                   4246:                           $scantronconf{Qstart}    => 'Qstart',
                   4247:                         );
                   4248:             my @ordered;
                   4249:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4250:                 push(@ordered,$bynum{$item});
                   4251:             }
                   4252:             my %mapstart = (
                   4253:                               CODEstart => 'CODE',
                   4254:                               IDstart   => 'ID',
                   4255:                               PaperID   => 'PaperID',
                   4256:                               FirstName => 'FirstName',
                   4257:                               LastName  => 'LastName',
                   4258:                               Qstart    => 'FirstQuestion',
                   4259:                            );
                   4260:             my %maplength = (
                   4261:                               CODEstart => 'CODElength',
                   4262:                               IDstart   => 'IDlength',
                   4263:                               PaperID   => 'PaperIDlength',
                   4264:                               FirstName => 'FirstNamelength',
                   4265:                               LastName  => 'LastNamelength',
                   4266:             );
                   4267:             if (open(my $fh,'<',$fullpath)) {
                   4268:                 my $output;
                   4269:                 my %lettdig = &letter_to_digits();
                   4270:                 my %diglett = reverse(%lettdig);
                   4271:                 my $numletts = scalar(keys(%lettdig));
                   4272:                 my $num = 0;
                   4273:                 while (my $line=<$fh>) {
                   4274:                     $num ++;
                   4275:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4276:                     $line =~ s{[\r\n]+$}{};
                   4277:                     my %found;
                   4278:                     my @values = split(/,/,$line);
                   4279:                     my ($qstart,$record);
                   4280:                     for (my $i=0; $i<@values; $i++) {
                   4281:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4282:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4283:                             if ($values[$i] eq '') {
                   4284:                                 $values[$i] = $scantronconf{'Qoff'};
                   4285:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4286:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4287:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4288:                                 }
                   4289:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4290:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4291:                                     $values[$i] = $diglett{$values[$i]};
                   4292:                                 }
                   4293:                             } else {
                   4294:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4295:                                     my $digit;
                   4296:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4297:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4298:                                         if ($values[$i] eq 'J') {
                   4299:                                             $digit += $numletts;
                   4300:                                         }
                   4301:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4302:                                         $digit = $values[$i]-1;
                   4303:                                         if ($values[$i] eq '0') {
                   4304:                                             $digit += $numletts;
                   4305:                                         }
                   4306:                                     }
                   4307:                                     my $qval='';
                   4308:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4309:                                         if ($j == $digit) {
                   4310:                                             $qval .= $scantronconf{'Qon'};
                   4311:                                         } else {
                   4312:                                             $qval .= $scantronconf{'Qoff'};
                   4313:                                         }
                   4314:                                     }
                   4315:                                     $values[$i] = $qval;
                   4316:                                 }
                   4317:                             }
                   4318:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4319:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4320:                             }
                   4321:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4322:                             if ($numblank > 0) {
                   4323:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4324:                             }
                   4325:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4326:                                 $qstart = $i;
                   4327:                                 $found{$csvbynum{$i}} = $values[$i];
                   4328:                             } else {
                   4329:                                 $found{'FirstQuestion'} .= $values[$i];
                   4330:                             }
                   4331:                         } elsif (exists($csvbynum{$i})) {
                   4332:                             if ($csvoptions{'rem'}) {
                   4333:                                 $values[$i] =~ s/^\s+//;
                   4334:                             }
                   4335:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4336:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4337:                                     $values[$i] = '0'.$values[$i];
                   4338:                                 }
                   4339:                             }
                   4340:                             $found{$csvbynum{$i}} = $values[$i];
                   4341:                         }
                   4342:                     }
                   4343:                     foreach my $item (@ordered) {
                   4344:                         my $currlength = 1+length($record);
                   4345:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4346:                         if ($numspaces > 0) {
                   4347:                             $record .= (' ' x $numspaces);
                   4348:                         }
                   4349:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4350:                             unless ($item eq 'Qstart') {
                   4351:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4352:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4353:                                 }
                   4354:                             }
                   4355:                             $record .= $found{$mapstart{$item}};
                   4356:                         }
                   4357:                     }
                   4358:                     $output .= "$record\n";
                   4359:                 }
                   4360:                 close($fh);
                   4361:                 if ($output) {
                   4362:                     if (open(my $fh,'>',$fullpath)) {
                   4363:                         print $fh $output;
                   4364:                         close($fh);
                   4365:                     }
                   4366:                 }
                   4367:             }
                   4368:         }
                   4369:         return;
                   4370:     }
                   4371: }
                   4372: 
                   4373: sub letter_to_digits {
                   4374:     my %lettdig = (
                   4375:                     A => 1,
                   4376:                     B => 2,
                   4377:                     C => 3,
                   4378:                     D => 4,
                   4379:                     E => 5,
                   4380:                     F => 6,
                   4381:                     G => 7,
                   4382:                     H => 8,
                   4383:                     I => 9,
                   4384:                     J => 0,
                   4385:                   );
                   4386:     return %lettdig;
                   4387: }
                   4388: 
                   4389: sub get_scantron_config {
                   4390:     my ($which,$cdom) = @_;
                   4391:     my @lines = &get_scantronformat_file($cdom);
                   4392:     my %config;
                   4393:     #FIXME probably should move to XML it has already gotten a bit much now
                   4394:     foreach my $line (@lines) {
                   4395:         my ($name,$descrip)=split(/:/,$line);
                   4396:         if ($name ne $which ) { next; }
                   4397:         chomp($line);
                   4398:         my @config=split(/:/,$line);
                   4399:         $config{'name'}=$config[0];
                   4400:         $config{'description'}=$config[1];
                   4401:         $config{'CODElocation'}=$config[2];
                   4402:         $config{'CODEstart'}=$config[3];
                   4403:         $config{'CODElength'}=$config[4];
                   4404:         $config{'IDstart'}=$config[5];
                   4405:         $config{'IDlength'}=$config[6];
                   4406:         $config{'Qstart'}=$config[7];
                   4407:         $config{'Qlength'}=$config[8];
                   4408:         $config{'Qoff'}=$config[9];
                   4409:         $config{'Qon'}=$config[10];
                   4410:         $config{'PaperID'}=$config[11];
                   4411:         $config{'PaperIDlength'}=$config[12];
                   4412:         $config{'FirstName'}=$config[13];
                   4413:         $config{'FirstNamelength'}=$config[14];
                   4414:         $config{'LastName'}=$config[15];
                   4415:         $config{'LastNamelength'}=$config[16];
                   4416:         $config{'BubblesPerRow'}=$config[17];
                   4417:         last;
                   4418:     }
                   4419:     return %config;
                   4420: }
                   4421: 
                   4422: sub get_scantronformat_file {
                   4423:     my ($cdom) = @_;
                   4424:     if ($cdom eq '') {
                   4425:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4426:     }
                   4427:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4428:     my $gottab = 0;
                   4429:     my @lines;
                   4430:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4431:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4432:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4433:             if ($formatfile ne '-1') {
                   4434:                 @lines = split("\n",$formatfile,-1);
                   4435:                 $gottab = 1;
                   4436:             }
                   4437:         }
                   4438:     }
                   4439:     if (!$gottab) {
                   4440:         my $confname = $cdom.'-domainconfig';
                   4441:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4442:         my $formatfile = &getfile($default);
                   4443:         if ($formatfile ne '-1') {
                   4444:             @lines = split("\n",$formatfile,-1);
                   4445:             $gottab = 1;
                   4446:         }
                   4447:     }
                   4448:     if (!$gottab) {
                   4449:         my @domains = &current_machine_domains();
                   4450:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4451:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4452:                 @lines = <$fh>;
                   4453:                 close($fh);
                   4454:             }
                   4455:         } else {
                   4456:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4457:                 @lines = <$fh>;
                   4458:                 close($fh);
                   4459:             }
                   4460:         }
                   4461:     }
                   4462:     return @lines;
                   4463: }
                   4464: 
1.493     albertel 4465: sub removeuploadedurl {
1.984     neumanie 4466:     my ($url)=@_;	
                   4467:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4468:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4469: }
                   4470: 
                   4471: sub removeuserfile {
                   4472:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4473:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4474:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4475:     if ($result eq 'ok') {	
1.798     raeburn  4476:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4477:             my $metafile = $fname.'.meta';
                   4478:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4479: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4480:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4481:             my $sqlresult = 
1.823     albertel 4482:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4483:                                         'portfolio_metadata',$group,
                   4484:                                         'delete');
1.798     raeburn  4485:         }
                   4486:     }
                   4487:     return $result;
1.257     www      4488: }
1.15      www      4489: 
1.530     albertel 4490: sub mkdiruserfile {
                   4491:     my ($docuname,$docudom,$dir)=@_;
                   4492:     my $home=&homeserver($docuname,$docudom);
                   4493:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4494: }
                   4495: 
1.531     albertel 4496: sub renameuserfile {
                   4497:     my ($docuname,$docudom,$old,$new)=@_;
                   4498:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4499:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4500:                         &escape("$old").':'.&escape("$new"),$home);
                   4501:     if ($result eq 'ok') {
                   4502:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4503:             my $oldmeta = $old.'.meta';
                   4504:             my $newmeta = $new.'.meta';
                   4505:             my $metaresult = 
                   4506:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4507: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4508:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4509:             my $sqlresult = 
1.823     albertel 4510:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4511:                                         'portfolio_metadata',$group,
                   4512:                                         'delete');
1.798     raeburn  4513:         }
                   4514:     }
                   4515:     return $result;
1.531     albertel 4516: }
                   4517: 
1.14      www      4518: # ------------------------------------------------------------------------- Log
                   4519: 
                   4520: sub log {
                   4521:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4522:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4523: }
                   4524: 
                   4525: # ------------------------------------------------------------------ Course Log
1.352     www      4526: #
                   4527: # This routine flushes several buffers of non-mission-critical nature
                   4528: #
1.157     www      4529: 
                   4530: sub flushcourselogs {
1.352     www      4531:     &logthis('Flushing log buffers');
                   4532: #
                   4533: # course logs
                   4534: # This is a log of all transactions in a course, which can be used
                   4535: # for data mining purposes
                   4536: #
                   4537: # It also collects the courseid database, which lists last transaction
                   4538: # times and course titles for all courseids
                   4539: #
                   4540:     my %courseidbuffer=();
1.921     raeburn  4541:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4542:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4543: 		          &escape($courselogs{$crsid}),
                   4544: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4545: 	    delete $courselogs{$crsid};
                   4546:         } else {
                   4547:             &logthis('Failed to flush log buffer for '.$crsid);
                   4548:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4549:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4550:                         " exceeded maximum size, deleting.</font>");
                   4551:                delete $courselogs{$crsid};
                   4552:             }
1.352     www      4553:         }
1.920     raeburn  4554:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4555:             'description' => $coursedescrbuf{$crsid},
                   4556:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4557:             'type'        => $coursetypebuf{$crsid},
                   4558:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4559:         };
1.191     harris41 4560:     }
1.352     www      4561: #
                   4562: # Write course id database (reverse lookup) to homeserver of courses 
                   4563: # Is used in pickcourse
                   4564: #
1.840     albertel 4565:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4566:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4567:                                     $courseidbuffer{$crs_home},
                   4568:                                     $crs_home,'timeonly');
1.352     www      4569:     }
                   4570: #
                   4571: # File accesses
                   4572: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4573: #
1.449     matthew  4574:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4575:         if ($entry =~ /___count$/) {
                   4576:             my ($dom,$name);
1.807     albertel 4577:             ($dom,$name,undef)=
1.811     albertel 4578: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4579:             if (! defined($dom) || $dom eq '' || 
                   4580:                 ! defined($name) || $name eq '') {
1.620     albertel 4581:                 my $cid = $env{'request.course.id'};
                   4582:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4583:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4584:             }
1.450     matthew  4585:             my $value = $accesshash{$entry};
                   4586:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4587:             my %temphash=($url => $value);
1.449     matthew  4588:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4589:             if ($result eq 'ok') {
                   4590:                 delete $accesshash{$entry};
                   4591:             }
                   4592:         } else {
1.811     albertel 4593:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4594:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4595:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4596:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4597:                 delete $accesshash{$entry};
                   4598:             }
1.185     www      4599:         }
1.191     harris41 4600:     }
1.352     www      4601: #
                   4602: # Roles
                   4603: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4604: #
1.800     albertel 4605:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4606:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4607: 	    split(/\:/,$entry);
                   4608:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4609:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4610:                 $rudom,$runame) eq 'ok') {
                   4611: 	    delete $userrolehash{$entry};
                   4612:         }
                   4613:     }
1.662     raeburn  4614: #
1.1172.2.90  raeburn  4615: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4616: #
                   4617:     my %domrolebuffer = ();
1.1000    raeburn  4618:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4619:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4620:         if ($domrolebuffer{$rudom}) {
                   4621:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4622:                       '='.&escape($domainrolehash{$entry});
                   4623:         } else {
                   4624:             $domrolebuffer{$rudom}.=&escape($entry).
                   4625:                       '='.&escape($domainrolehash{$entry});
                   4626:         }
                   4627:         delete $domainrolehash{$entry};
                   4628:     }
                   4629:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4630:         my %servers;
                   4631:         if (defined(&domain($dom,'primary'))) {
                   4632:             my $primary=&domain($dom,'primary');
                   4633:             my $hostname=&hostname($primary);
                   4634:             $servers{$primary} = $hostname;
                   4635:         } else {
                   4636:             %servers = &get_servers($dom,'library');
                   4637:         }
1.841     albertel 4638: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4639: 	    if (&reply('domroleput:'.$dom.':'.
                   4640: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4641: 	        last;
                   4642: 	    } else {
1.841     albertel 4643: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4644: 	    }
1.662     raeburn  4645:         }
                   4646:     }
1.186     www      4647:     $dumpcount++;
1.157     www      4648: }
                   4649: 
                   4650: sub courselog {
                   4651:     my $what=shift;
1.158     www      4652:     $what=time.':'.$what;
1.620     albertel 4653:     unless ($env{'request.course.id'}) { return ''; }
                   4654:     $coursedombuf{$env{'request.course.id'}}=
                   4655:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4656:     $coursenumbuf{$env{'request.course.id'}}=
                   4657:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4658:     $coursehombuf{$env{'request.course.id'}}=
                   4659:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4660:     $coursedescrbuf{$env{'request.course.id'}}=
                   4661:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4662:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4663:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4664:     $courseownerbuf{$env{'request.course.id'}}=
                   4665:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4666:     $coursetypebuf{$env{'request.course.id'}}=
                   4667:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4668:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4669: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4670:     } else {
1.620     albertel 4671: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4672:     }
1.620     albertel 4673:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4674: 	&flushcourselogs();
                   4675:     }
1.158     www      4676: }
                   4677: 
                   4678: sub courseacclog {
                   4679:     my $fnsymb=shift;
1.620     albertel 4680:     unless ($env{'request.course.id'}) { return ''; }
                   4681:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4682:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4683:         $what.=':POST';
1.583     matthew  4684:         # FIXME: Probably ought to escape things....
1.800     albertel 4685: 	foreach my $key (keys(%env)) {
                   4686:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4687:                 my $formitem = $1;
                   4688:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4689:                     $what.=':'.$formitem.'='.$env{$key};
                   4690:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4691:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4692:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4693:                     } else {
                   4694:                         $what.=':'.$formitem.'='.$env{$key};
                   4695:                     }
1.975     raeburn  4696:                 }
1.158     www      4697:             }
1.191     harris41 4698:         }
1.583     matthew  4699:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4700:         # FIXME: We should not be depending on a form parameter that someone
                   4701:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4702:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4703:             $what.= ':POST';
                   4704:             # FIXME: Probably ought to escape things....
                   4705:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4706:                                  'crsdiscuss') {
1.620     albertel 4707:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4708:             }
                   4709:         }
1.158     www      4710:     }
                   4711:     &courselog($what);
1.149     www      4712: }
                   4713: 
1.185     www      4714: sub countacc {
                   4715:     my $url=&declutter(shift);
1.458     matthew  4716:     return if (! defined($url) || $url eq '');
1.620     albertel 4717:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4718: #
                   4719: # Mark that this url was used in this course
                   4720: #
1.620     albertel 4721:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4722: #
                   4723: # Increase the access count for this resource in this child process
                   4724: #
1.281     www      4725:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4726:     $accesshash{$key}++;
1.185     www      4727: }
1.349     www      4728: 
1.361     www      4729: sub linklog {
                   4730:     my ($from,$to)=@_;
                   4731:     $from=&declutter($from);
                   4732:     $to=&declutter($to);
                   4733:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4734:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4735: }
1.1160    www      4736: 
                   4737: sub statslog {
                   4738:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4739:     if ($users<2) { return; }
                   4740:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4741:             'course'       => $env{'request.course.id'},
                   4742:             'sections'     => '"all"',
                   4743:             'num_students' => $users,
                   4744:             'part'         => $part,
                   4745:             'symb'         => $symb,
                   4746:             'mean_tries'   => $av_attempts,
                   4747:             'deg_of_diff'  => $degdiff});
                   4748:     foreach my $key (keys(%dynstore)) {
                   4749:         $accesshash{$key}=$dynstore{$key};
                   4750:     }
                   4751: }
1.361     www      4752:   
1.349     www      4753: sub userrolelog {
                   4754:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4755:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4756:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4757:        $userrolehash
                   4758:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4759:                     =$tend.':'.$tstart;
1.662     raeburn  4760:     }
1.1169    droeschl 4761:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4762:        $userrolehash
                   4763:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4764:                     =$tend.':'.$tstart;
                   4765:     }
1.1172.2.90  raeburn  4766:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4767:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4768:        $domainrolehash
                   4769:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4770:                     = $tend.':'.$tstart;
                   4771:     }
1.351     www      4772: }
                   4773: 
1.957     raeburn  4774: sub courserolelog {
                   4775:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4776:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4777:         my $cdom = $1;
                   4778:         my $cnum = $2;
                   4779:         my $sec = $3;
                   4780:         my $namespace = 'rolelog';
                   4781:         my %storehash = (
                   4782:                            role    => $trole,
                   4783:                            start   => $tstart,
                   4784:                            end     => $tend,
                   4785:                            selfenroll => $selfenroll,
                   4786:                            context    => $context,
                   4787:                         );
                   4788:         if ($trole eq 'gr') {
                   4789:             $namespace = 'groupslog';
                   4790:             $storehash{'group'} = $sec;
                   4791:         } else {
                   4792:             $storehash{'section'} = $sec;
                   4793:         }
                   4794:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4795:                    $domain,$cnum,$cdom);
                   4796:         if (($trole ne 'st') || ($sec ne '')) {
                   4797:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4798:         }
                   4799:     }
                   4800:     return;
                   4801: }
                   4802: 
1.1172.2.9  raeburn  4803: sub domainrolelog {
                   4804:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4805:     if ($area =~ m{^/($match_domain)/$}) {
                   4806:         my $cdom = $1;
                   4807:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4808:         my $namespace = 'rolelog';
                   4809:         my %storehash = (
                   4810:                            role    => $trole,
                   4811:                            start   => $tstart,
                   4812:                            end     => $tend,
                   4813:                            context => $context,
                   4814:                         );
                   4815:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4816:                    $domain,$domconfiguser,$cdom);
                   4817:     }
                   4818:     return;
                   4819: 
                   4820: }
                   4821: 
                   4822: sub coauthorrolelog {
                   4823:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4824:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4825:         my $audom = $1;
                   4826:         my $auname = $2;
                   4827:         my $namespace = 'rolelog';
                   4828:         my %storehash = (
                   4829:                            role    => $trole,
                   4830:                            start   => $tstart,
                   4831:                            end     => $tend,
                   4832:                            context => $context,
                   4833:                         );
                   4834:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4835:                    $domain,$auname,$audom);
                   4836:     }
                   4837:     return;
                   4838: }
                   4839: 
1.351     www      4840: sub get_course_adv_roles {
1.948     raeburn  4841:     my ($cid,$codes) = @_;
1.620     albertel 4842:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4843:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4844:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4845:     my %nothide=();
1.800     albertel 4846:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4847:         if ($user !~ /:/) {
                   4848: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4849:         } else {
                   4850:             $nothide{$user}=1;
                   4851:         }
1.470     www      4852:     }
1.1172.2.23  raeburn  4853:     my @possdoms = ($coursehash{'domain'});
                   4854:     if ($coursehash{'checkforpriv'}) {
                   4855:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4856:     }
1.351     www      4857:     my %returnhash=();
                   4858:     my %dumphash=
                   4859:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4860:     my $now=time;
1.997     raeburn  4861:     my %privileged;
1.1000    raeburn  4862:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4863: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4864:         if (($tstart) && ($tstart<0)) { next; }
                   4865:         if (($tend) && ($tend<$now)) { next; }
                   4866:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4867:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4868: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4869:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4870:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4871: 	if ($role eq 'cr') { next; }
1.948     raeburn  4872:         if ($codes) {
                   4873:             if ($section) { $role .= ':'.$section; }
                   4874:             if ($returnhash{$role}) {
                   4875:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4876:             } else {
                   4877:                 $returnhash{$role}=$username.':'.$domain;
                   4878:             }
1.351     www      4879:         } else {
1.988     raeburn  4880:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4881:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4882:             if ($returnhash{$key}) {
                   4883: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4884:             } else {
                   4885:                 $returnhash{$key}=$username.':'.$domain;
                   4886:             }
1.351     www      4887:         }
1.948     raeburn  4888:     }
1.400     www      4889:     return %returnhash;
                   4890: }
                   4891: 
                   4892: sub get_my_roles {
1.937     raeburn  4893:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4894:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4895:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4896:     my (%dumphash,%nothide);
1.1086    raeburn  4897:     if ($context eq 'userroles') {
1.1166    raeburn  4898:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4899:     } else {
1.1172.2.23  raeburn  4900:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4901:         if ($hidepriv) {
                   4902:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4903:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4904:                 if ($user !~ /:/) {
                   4905:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4906:                 } else {
                   4907:                     $nothide{$user} = 1;
                   4908:                 }
                   4909:             }
                   4910:         }
1.858     raeburn  4911:     }
1.400     www      4912:     my %returnhash=();
                   4913:     my $now=time;
1.999     raeburn  4914:     my %privileged;
1.800     albertel 4915:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4916:         my ($role,$tend,$tstart);
                   4917:         if ($context eq 'userroles') {
1.1149    raeburn  4918:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4919: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4920:         } else {
                   4921:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4922:         }
1.400     www      4923:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4924:         my $status = 'active';
1.939     raeburn  4925:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4926:             $status = 'previous';
                   4927:         } 
                   4928:         if (($tstart) && ($now<$tstart)) {
                   4929:             $status = 'future';
                   4930:         }
                   4931:         if (ref($types) eq 'ARRAY') {
                   4932:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4933:                 next;
                   4934:             } 
                   4935:         } else {
                   4936:             if ($status ne 'active') {
                   4937:                 next;
                   4938:             }
                   4939:         }
1.867     raeburn  4940:         my ($rolecode,$username,$domain,$section,$area);
                   4941:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4942:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4943:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4944:         } else {
                   4945:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4946:         }
1.832     raeburn  4947:         if (ref($roledoms) eq 'ARRAY') {
                   4948:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4949:                 next;
                   4950:             }
                   4951:         }
                   4952:         if (ref($roles) eq 'ARRAY') {
                   4953:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4954:                 if ($role =~ /^cr\//) {
                   4955:                     if (!grep(/^cr$/,@{$roles})) {
                   4956:                         next;
                   4957:                     }
1.1104    raeburn  4958:                 } elsif ($role =~ /^gr\//) {
                   4959:                     if (!grep(/^gr$/,@{$roles})) {
                   4960:                         next;
                   4961:                     }
1.922     raeburn  4962:                 } else {
                   4963:                     next;
                   4964:                 }
1.832     raeburn  4965:             }
1.867     raeburn  4966:         }
1.937     raeburn  4967:         if ($hidepriv) {
1.1172.2.23  raeburn  4968:             my @privroles = ('dc','su');
1.999     raeburn  4969:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4970:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4971:             } else {
1.1172.2.23  raeburn  4972:                 my $possdoms = [$domain];
                   4973:                 if (ref($roledoms) eq 'ARRAY') {
                   4974:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4975:                 }
1.1172.2.23  raeburn  4976:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4977:                     if (!$nothide{$username.':'.$domain}) {
                   4978:                         next;
                   4979:                     }
                   4980:                 }
1.937     raeburn  4981:             }
                   4982:         }
1.933     raeburn  4983:         if ($withsec) {
                   4984:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4985:                 $tstart.':'.$tend;
                   4986:         } else {
                   4987:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4988:         }
1.832     raeburn  4989:     }
1.373     www      4990:     return %returnhash;
1.399     www      4991: }
                   4992: 
1.1172.2.89  raeburn  4993: sub get_all_adhocroles {
                   4994:     my ($dom) = @_;
                   4995:     my @roles_by_num = ();
                   4996:     my %domdefaults = &get_domain_defaults($dom);
                   4997:     my (%description,%access_in_dom,%access_info);
                   4998:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4999:         my $count = 0;
                   5000:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5001:         my %ordered;
                   5002:         foreach my $role (sort(keys(%domcurrent))) {
                   5003:             my ($order,$desc,$access_in_dom);
                   5004:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5005:                 $order = $domcurrent{$role}{'order'};
                   5006:                 $desc = $domcurrent{$role}{'desc'};
                   5007:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5008:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5009:             }
                   5010:             if ($order eq '') {
                   5011:                 $order = $count;
                   5012:             }
                   5013:             $ordered{$order} = $role;
                   5014:             if ($desc ne '') {
                   5015:                 $description{$role} = $desc;
                   5016:             } else {
                   5017:                 $description{$role}= $role;
                   5018:             }
                   5019:             $count++;
                   5020:         }
                   5021:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5022:             push(@roles_by_num,$ordered{$item});
                   5023:         }
                   5024:     }
                   5025:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5026: }
                   5027: 
                   5028: sub get_my_adhocroles {
                   5029:     my ($cid,$checkreg) = @_;
                   5030:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5031:     if ($env{'request.course.id'} eq $cid) {
                   5032:         $cdom = $env{'course.'.$cid.'.domain'};
                   5033:         $cnum = $env{'course.'.$cid.'.num'};
                   5034:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5035:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5036:         $cdom = $1;
                   5037:         $cnum = $2;
                   5038:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5039:                                      $cdom,$cnum);
                   5040:     }
                   5041:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5042:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5043:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5044:         if ($rosterhash{$user} ne '') {
                   5045:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5046:             return ([],{}) if ($type eq 'auto');
                   5047:         }
                   5048:     }
                   5049:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5050:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5051:             my $then=$env{'user.login.time'};
                   5052:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5053:             if (!$update) {
                   5054:                 $update = $then;
                   5055:             }
                   5056:             my @liveroles;
                   5057:             foreach my $role ('dh','da') {
                   5058:                 if ($env{"user.role.$role./$cdom/"}) {
                   5059:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5060:                     my $limit = $update;
                   5061:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5062:                         $limit = $then;
                   5063:                     }
                   5064:                     my $activerole = 1;
                   5065:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5066:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5067:                     if ($activerole) {
                   5068:                         push(@liveroles,$role);
                   5069:                     }
                   5070:                 }
                   5071:             }
                   5072:             if (@liveroles) {
1.1172.2.89  raeburn  5073:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5074:                     my ($accessref,$accessinfo,%access_in_dom);
                   5075:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5076:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5077:                         if (@{$roles_by_num}) {
                   5078:                             my %settings;
                   5079:                             if ($env{'request.course.id'} eq $cid) {
                   5080:                                 foreach my $envkey (keys(%env)) {
                   5081:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5082:                                         $settings{$1} = $env{$envkey};
                   5083:                                     }
                   5084:                                 }
                   5085:                             } else {
                   5086:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5087:                             }
                   5088:                             my %setincrs;
                   5089:                             if ($settings{'internal.adhocaccess'}) {
                   5090:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5091:                             }
                   5092:                             my @statuses;
                   5093:                             if ($env{'environment.inststatus'}) {
                   5094:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5095:                             }
                   5096:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5097:                             if (ref($accessref) eq 'HASH') {
                   5098:                                 %access_in_dom = %{$accessref};
                   5099:                             }
                   5100:                             foreach my $role (@{$roles_by_num}) {
                   5101:                                 my ($curraccess,@okstatus,@personnel);
                   5102:                                 if ($setincrs{$role}) {
                   5103:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5104:                                     if ($curraccess eq 'status') {
                   5105:                                         @okstatus = split(/\&/,$rest);
                   5106:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5107:                                         @personnel = split(/\&/,$rest);
                   5108:                                     }
                   5109:                                 } else {
                   5110:                                     $curraccess = $access_in_dom{$role};
                   5111:                                     if (ref($accessinfo) eq 'HASH') {
                   5112:                                         if ($curraccess eq 'status') {
                   5113:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5114:                                                 @okstatus = @{$accessinfo->{$role}};
                   5115:                                             }
                   5116:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5117:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5118:                                                 @personnel = @{$accessinfo->{$role}};
                   5119:                                             }
                   5120:                                         }
                   5121:                                     }
                   5122:                                 }
                   5123:                                 if ($curraccess eq 'none') {
                   5124:                                     next;
                   5125:                                 } elsif ($curraccess eq 'all') {
                   5126:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5127:                                 } elsif ($curraccess eq 'dh') {
                   5128:                                     if (grep(/^dh$/,@liveroles)) {
                   5129:                                         push(@possroles,$role);
                   5130:                                     } else {
                   5131:                                         next;
                   5132:                                     }
                   5133:                                 } elsif ($curraccess eq 'da') {
                   5134:                                     if (grep(/^da$/,@liveroles)) {
                   5135:                                         push(@possroles,$role);
                   5136:                                     } else {
                   5137:                                         next;
                   5138:                                     }
1.1172.2.89  raeburn  5139:                                 } elsif ($curraccess eq 'status') {
                   5140:                                     if (@okstatus) {
                   5141:                                         if (!@statuses) {
                   5142:                                             if (grep(/^default$/,@okstatus)) {
                   5143:                                                 push(@possroles,$role);
                   5144:                                             }
                   5145:                                         } else {
                   5146:                                             foreach my $status (@okstatus) {
                   5147:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5148:                                                     push(@possroles,$role);
                   5149:                                                     last;
                   5150:                                                 }
                   5151:                                             }
                   5152:                                         }
                   5153:                                     }
                   5154:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5155:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5156:                                         if ($curraccess eq 'exc') {
                   5157:                                             push(@possroles,$role);
                   5158:                                         }
                   5159:                                     } elsif ($curraccess eq 'inc') {
                   5160:                                         push(@possroles,$role);
                   5161:                                     }
                   5162:                                 }
                   5163:                             }
                   5164:                         }
                   5165:                     }
                   5166:                 }
                   5167:             }
                   5168:         }
                   5169:     }
                   5170:     unless (ref($description) eq 'HASH') {
                   5171:         if (ref($roles_by_num) eq 'ARRAY') {
                   5172:             my %desc;
                   5173:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5174:             $description = \%desc;
                   5175:         } else {
                   5176:             $description = {};
                   5177:         }
                   5178:     }
                   5179:     return (\@possroles,$description);
                   5180: }
                   5181: 
1.399     www      5182: # ----------------------------------------------------- Frontpage Announcements
                   5183: #
                   5184: #
                   5185: 
                   5186: sub postannounce {
                   5187:     my ($server,$text)=@_;
1.844     albertel 5188:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5189:     unless ($text=~/\w/) { $text=''; }
                   5190:     return &reply('setannounce:'.&escape($text),$server);
                   5191: }
                   5192: 
                   5193: sub getannounce {
1.448     albertel 5194: 
1.1172.2.96  raeburn  5195:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5196: 	my $announcement='';
1.800     albertel 5197: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5198: 	close($fh);
1.399     www      5199: 	if ($announcement=~/\w/) { 
                   5200: 	    return 
                   5201:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5202:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5203: 	} else {
                   5204: 	    return '';
                   5205: 	}
                   5206:     } else {
                   5207: 	return '';
                   5208:     }
1.351     www      5209: }
1.353     www      5210: 
                   5211: # ---------------------------------------------------------- Course ID routines
                   5212: # Deal with domain's nohist_courseid.db files
                   5213: #
                   5214: 
                   5215: sub courseidput {
1.921     raeburn  5216:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5217:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5218:     my $outcome;
                   5219:     if ($caller eq 'timeonly') {
                   5220:         my $cids = '';
                   5221:         foreach my $item (keys(%$storehash)) {
                   5222:             $cids.=&escape($item).'&';
                   5223:         }
                   5224:         $cids=~s/\&$//;
                   5225:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5226:                           $coursehome);       
                   5227:     } else {
                   5228:         my $items = '';
                   5229:         foreach my $item (keys(%$storehash)) {
                   5230:             $items.= &escape($item).'='.
                   5231:                      &freeze_escape($$storehash{$item}).'&';
                   5232:         }
                   5233:         $items=~s/\&$//;
                   5234:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5235:                           $coursehome);
1.918     raeburn  5236:     }
                   5237:     if ($outcome eq 'unknown_cmd') {
                   5238:         my $what;
                   5239:         foreach my $cid (keys(%$storehash)) {
                   5240:             $what .= &escape($cid).'=';
1.921     raeburn  5241:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5242:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5243:             }
                   5244:             $what =~ s/\:$/&/;
                   5245:         }
                   5246:         $what =~ s/\&$//;  
                   5247:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5248:     } else {
                   5249:         return $outcome;
                   5250:     }
1.353     www      5251: }
                   5252: 
                   5253: sub courseiddump {
1.921     raeburn  5254:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5255:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5256:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5257:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5258:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5259:     my $as_hash = 1;
                   5260:     my %returnhash;
                   5261:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5262:     my %libserv = &all_library();
                   5263:     foreach my $tryserver (keys(%libserv)) {
                   5264:         if ( (  $hostidflag == 1 
                   5265: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5266: 	     || (!defined($hostidflag)) ) {
                   5267: 
1.918     raeburn  5268: 	    if (($domfilter eq '') ||
                   5269: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5270:                 my $rep;
                   5271:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5272:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5273:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5274:                                 &escape($descfilter), &escape($instcodefilter),
                   5275:                                 &escape($ownerfilter), &escape($coursefilter),
                   5276:                                 &escape($typefilter), &escape($regexp_ok),
                   5277:                                 $as_hash, &escape($selfenrollonly),
                   5278:                                 &escape($catfilter), $showhidden, $caller,
                   5279:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5280:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5281:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5282:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5283:                 } else {
                   5284:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5285:                              $sincefilter.':'.&escape($descfilter).':'.
                   5286:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5287:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5288:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5289:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5290:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5291:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5292:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5293:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5294:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5295:                 }
                   5296: 
1.918     raeburn  5297:                 my @pairs=split(/\&/,$rep);
                   5298:                 foreach my $item (@pairs) {
                   5299:                     my ($key,$value)=split(/\=/,$item,2);
                   5300:                     $key = &unescape($key);
                   5301:                     next if ($key =~ /^error: 2 /);
                   5302:                     my $result = &thaw_unescape($value);
                   5303:                     if (ref($result) eq 'HASH') {
                   5304:                         $returnhash{$key}=$result;
                   5305:                     } else {
1.921     raeburn  5306:                         my @responses = split(/:/,$value);
                   5307:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5308:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5309:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5310:                         }
1.1008    raeburn  5311:                     }
1.353     www      5312:                 }
                   5313:             }
                   5314:         }
                   5315:     }
                   5316:     return %returnhash;
                   5317: }
                   5318: 
1.1055    raeburn  5319: sub courselastaccess {
                   5320:     my ($cdom,$cnum,$hostidref) = @_;
                   5321:     my %returnhash;
                   5322:     if ($cdom && $cnum) {
                   5323:         my $chome = &homeserver($cnum,$cdom);
                   5324:         if ($chome ne 'no_host') {
                   5325:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5326:             &extract_lastaccess(\%returnhash,$rep);
                   5327:         }
                   5328:     } else {
                   5329:         if (!$cdom) { $cdom=''; }
                   5330:         my %libserv = &all_library();
                   5331:         foreach my $tryserver (keys(%libserv)) {
                   5332:             if (ref($hostidref) eq 'ARRAY') {
                   5333:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5334:             } 
                   5335:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5336:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5337:                 &extract_lastaccess(\%returnhash,$rep);
                   5338:             }
                   5339:         }
                   5340:     }
                   5341:     return %returnhash;
                   5342: }
                   5343: 
                   5344: sub extract_lastaccess {
                   5345:     my ($returnhash,$rep) = @_;
                   5346:     if (ref($returnhash) eq 'HASH') {
                   5347:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5348:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5349:                  $rep eq '') {
                   5350:             my @pairs=split(/\&/,$rep);
                   5351:             foreach my $item (@pairs) {
                   5352:                 my ($key,$value)=split(/\=/,$item,2);
                   5353:                 $key = &unescape($key);
                   5354:                 next if ($key =~ /^error: 2 /);
                   5355:                 $returnhash->{$key} = &thaw_unescape($value);
                   5356:             }
                   5357:         }
                   5358:     }
                   5359:     return;
                   5360: }
                   5361: 
1.658     raeburn  5362: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5363: 
                   5364: sub dcmailput {
1.685     raeburn  5365:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5366:     my $status = &Apache::lonnet::critical(
1.740     www      5367:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5368:        &escape($message),$server);
1.662     raeburn  5369:     return $status;
                   5370: }
                   5371: 
1.658     raeburn  5372: sub dcmaildump {
                   5373:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5374:     my %returnhash=();
1.846     albertel 5375: 
                   5376:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5377:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5378:                                                          &escape($enddate).':';
                   5379: 	my @esc_senders=map { &escape($_)} @$senders;
                   5380: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5381: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5382:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5383:             if (($key) && ($value)) {
                   5384:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5385:             }
                   5386:         }
                   5387:     }
                   5388:     return %returnhash;
                   5389: }
1.662     raeburn  5390: # ---------------------------------------------------------- Domain roles
                   5391: 
                   5392: sub get_domain_roles {
                   5393:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5394:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5395:         $startdate = '.';
                   5396:     }
1.1018    raeburn  5397:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5398:         $enddate = '.';
                   5399:     }
1.922     raeburn  5400:     my $rolelist;
                   5401:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5402:         $rolelist = join('&',@{$roles});
1.922     raeburn  5403:     }
1.662     raeburn  5404:     my %personnel = ();
1.841     albertel 5405: 
                   5406:     my %servers = &get_servers($dom,'library');
                   5407:     foreach my $tryserver (keys(%servers)) {
                   5408: 	%{$personnel{$tryserver}}=();
                   5409: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5410: 					    &escape($startdate).':'.
                   5411: 					    &escape($enddate).':'.
                   5412: 					    &escape($rolelist), $tryserver))) {
                   5413: 	    my ($key,$value) = split(/\=/,$line,2);
                   5414: 	    if (($key) && ($value)) {
                   5415: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5416: 	    }
                   5417: 	}
1.662     raeburn  5418:     }
                   5419:     return %personnel;
                   5420: }
1.658     raeburn  5421: 
1.1172.2.89  raeburn  5422: sub get_active_domroles {
                   5423:     my ($dom,$roles) = @_;
                   5424:     return () unless (ref($roles) eq 'ARRAY');
                   5425:     my $now = time;
                   5426:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5427:     my %domroles;
                   5428:     foreach my $server (keys(%dompersonnel)) {
                   5429:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5430:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5431:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5432:         }
                   5433:     }
                   5434:     return %domroles;
                   5435: }
                   5436: 
1.1057    www      5437: # ----------------------------------------------------------- Interval timing 
1.149     www      5438: 
1.1153    www      5439: {
                   5440: # Caches needed for speedup of navmaps
                   5441: # We don't want to cache this for very long at all (5 seconds at most)
                   5442: # 
                   5443: # The user for whom we cache
                   5444: my $cachedkey='';
                   5445: # The cached times for this user
                   5446: my %cachedtimes=();
                   5447: # When this was last done
1.1172.2.66  raeburn  5448: my $cachedtime='';
1.1153    www      5449: 
                   5450: sub load_all_first_access {
1.1154    raeburn  5451:     my ($uname,$udom)=@_;
1.1156    www      5452:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5453:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5454:         return;
                   5455:     }
                   5456:     $cachedtime=time;
                   5457:     $cachedkey=$uname.':'.$udom;
                   5458:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5459: }
                   5460: 
1.504     albertel 5461: sub get_first_access {
1.1162    raeburn  5462:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5463:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5464:     if ($argsymb) { $symb=$argsymb; }
                   5465:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5466:     if ($argmap) { $map = $argmap; }
1.926     albertel 5467:     if ($type eq 'course') {
                   5468: 	$res='course';
                   5469:     } elsif ($type eq 'map') {
1.588     albertel 5470: 	$res=&symbread($map);
                   5471:     } else {
                   5472: 	$res=$symb;
                   5473:     }
1.1153    www      5474:     &load_all_first_access($uname,$udom);
                   5475:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5476: }
                   5477: 
                   5478: sub set_first_access {
1.1162    raeburn  5479:     my ($type,$interval)=@_;
1.790     albertel 5480:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5481:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5482:     if ($type eq 'course') {
                   5483: 	$res='course';
                   5484:     } elsif ($type eq 'map') {
1.588     albertel 5485: 	$res=&symbread($map);
                   5486:     } else {
                   5487: 	$res=$symb;
                   5488:     }
1.1153    www      5489:     $cachedkey='';
1.1162    raeburn  5490:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5491:     if ($firstaccess) {
                   5492:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5493:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5494:                  "in $courseid");
                   5495:         return 'already_set';
                   5496:     } else {
1.1162    raeburn  5497:         my $start = time;
                   5498: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5499:                           $udom,$uname);
                   5500:         if ($putres eq 'ok') {
                   5501:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5502:                  $udom,$uname); 
                   5503:             &appenv(
                   5504:                      {
                   5505:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5506:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5507:                      }
                   5508:                   );
1.1172.2.97  raeburn  5509:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5510:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5511:             }
1.1172.2.102  raeburn  5512:         } elsif ($putres ne 'refused') {
                   5513:             &logthis("Result: $putres when attempting to set first access time ".
                   5514:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5515:         }
                   5516:         return $putres;
1.505     albertel 5517:     }
                   5518:     return 'already_set';
1.504     albertel 5519: }
1.1153    www      5520: }
1.1172.2.32  raeburn  5521: 
                   5522: sub checkout {
                   5523:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5524:     my $now=time;
                   5525:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5526:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5527:     my $infostr=&escape(
                   5528:                  'CHECKOUTTOKEN&'.
                   5529:                  $tuname.'&'.
                   5530:                  $tudom.'&'.
                   5531:                  $tcrsid.'&'.
                   5532:                  $symb.'&'.
1.1172.2.134  raeburn  5533:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5534:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5535:     if ($token=~/^error\:/) {
                   5536:         &logthis("<font color=\"blue\">WARNING: ".
                   5537:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5538:                  "</font>");
                   5539:         return '';
                   5540:     }
                   5541: 
                   5542:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5543:     $token=~tr/a-z/A-Z/;
                   5544: 
                   5545:     my %infohash=('resource.0.outtoken' => $token,
                   5546:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5547:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5548: 
                   5549:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5550:        return '';
                   5551:     } else {
                   5552:         &logthis("<font color=\"blue\">WARNING: ".
                   5553:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5554:                  "</font>");
                   5555:     }
                   5556: 
                   5557:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5558:                          &escape('Checkout '.$infostr.' - '.
                   5559:                                                  $token)) ne 'ok') {
                   5560:         return '';
                   5561:     } else {
                   5562:         &logthis("<font color=\"blue\">WARNING: ".
                   5563:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5564:                  "</font>");
                   5565:     }
                   5566:     return $token;
                   5567: }
                   5568: 
                   5569: # ------------------------------------------------------------ Check in an item
                   5570: 
                   5571: sub checkin {
                   5572:     my $token=shift;
                   5573:     my $now=time;
                   5574:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5575:     $lonhost=~tr/A-Z/a-z/;
                   5576:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5577:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5578:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5579:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5580:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5581: 
                   5582:     unless (($tuname) && ($tudom)) {
                   5583:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5584:         return '';
                   5585:     }
                   5586: 
                   5587:     unless (&allowed('mgr',$tcrsid)) {
                   5588:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5589:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5590:         return '';
                   5591:     }
                   5592: 
                   5593:     my %infohash=('resource.0.intoken' => $token,
                   5594:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5595:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5596: 
                   5597:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5598:        return '';
                   5599:     }
                   5600: 
                   5601:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5602:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5603:         return '';
                   5604:     }
                   5605: 
                   5606:     return ($symb,$tuname,$tudom,$tcrsid);
                   5607: }
                   5608: 
1.110     www      5609: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5610: 
                   5611: sub expirespread {
                   5612:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5613:     my $cid=$env{'request.course.id'}; 
1.110     www      5614:     if ($cid) {
                   5615:        my $now=time;
                   5616:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5617:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5618:                             $env{'course.'.$cid.'.num'}.
1.110     www      5619: 	        	    ':nohist_expirationdates:'.
                   5620:                             &escape($key).'='.$now,
1.620     albertel 5621:                             $env{'course.'.$cid.'.home'})
1.110     www      5622:     }
                   5623:     return 'ok';
1.14      www      5624: }
                   5625: 
1.109     www      5626: # ----------------------------------------------------- Devalidate Spreadsheets
                   5627: 
                   5628: sub devalidate {
1.325     www      5629:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5630:     my $cid=$env{'request.course.id'}; 
1.109     www      5631:     if ($cid) {
1.391     matthew  5632:         # delete the stored spreadsheets for
                   5633:         # - the student level sheet of this user in course's homespace
                   5634:         # - the assessment level sheet for this resource 
                   5635:         #   for this user in user's homespace
1.553     albertel 5636: 	# - current conditional state info
1.325     www      5637: 	my $key=$uname.':'.$udom.':';
1.109     www      5638:         my $status=
1.299     matthew  5639: 	    &del('nohist_calculatedsheets',
1.391     matthew  5640: 		 [$key.'studentcalc:'],
1.620     albertel 5641: 		 $env{'course.'.$cid.'.domain'},
                   5642: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5643: 		.' '.
                   5644: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5645: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5646:         unless ($status eq 'ok ok') {
                   5647:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5648:                     $uname.' at '.$udom.' for '.
1.109     www      5649: 		    $symb.': '.$status);
1.133     albertel 5650:         }
1.553     albertel 5651: 	&delenv('user.state.'.$cid);
1.109     www      5652:     }
                   5653: }
                   5654: 
1.265     albertel 5655: sub get_scalar {
                   5656:     my ($string,$end) = @_;
                   5657:     my $value;
                   5658:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5659: 	$value = $1;
                   5660:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5661: 	$value = $1;
                   5662:     }
                   5663:     return &unescape($value);
                   5664: }
                   5665: 
                   5666: sub array2str {
                   5667:   my (@array) = @_;
                   5668:   my $result=&arrayref2str(\@array);
                   5669:   $result=~s/^__ARRAY_REF__//;
                   5670:   $result=~s/__END_ARRAY_REF__$//;
                   5671:   return $result;
                   5672: }
                   5673: 
1.204     albertel 5674: sub arrayref2str {
                   5675:   my ($arrayref) = @_;
1.265     albertel 5676:   my $result='__ARRAY_REF__';
1.204     albertel 5677:   foreach my $elem (@$arrayref) {
1.265     albertel 5678:     if(ref($elem) eq 'ARRAY') {
                   5679:       $result.=&arrayref2str($elem).'&';
                   5680:     } elsif(ref($elem) eq 'HASH') {
                   5681:       $result.=&hashref2str($elem).'&';
                   5682:     } elsif(ref($elem)) {
                   5683:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5684:     } else {
                   5685:       $result.=&escape($elem).'&';
                   5686:     }
                   5687:   }
                   5688:   $result=~s/\&$//;
1.265     albertel 5689:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5690:   return $result;
                   5691: }
                   5692: 
1.168     albertel 5693: sub hash2str {
1.204     albertel 5694:   my (%hash) = @_;
                   5695:   my $result=&hashref2str(\%hash);
1.265     albertel 5696:   $result=~s/^__HASH_REF__//;
                   5697:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5698:   return $result;
                   5699: }
                   5700: 
                   5701: sub hashref2str {
                   5702:   my ($hashref)=@_;
1.265     albertel 5703:   my $result='__HASH_REF__';
1.800     albertel 5704:   foreach my $key (sort(keys(%$hashref))) {
                   5705:     if (ref($key) eq 'ARRAY') {
                   5706:       $result.=&arrayref2str($key).'=';
                   5707:     } elsif (ref($key) eq 'HASH') {
                   5708:       $result.=&hashref2str($key).'=';
                   5709:     } elsif (ref($key)) {
1.265     albertel 5710:       $result.='=';
1.800     albertel 5711:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5712:     } else {
1.1132    raeburn  5713: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5714:     }
                   5715: 
1.800     albertel 5716:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5717:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5718:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5719:       $result.=&hashref2str($hashref->{$key}).'&';
                   5720:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5721:        $result.='&';
1.800     albertel 5722:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5723:     } else {
1.800     albertel 5724:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5725:     }
                   5726:   }
1.168     albertel 5727:   $result=~s/\&$//;
1.265     albertel 5728:   $result .= '__END_HASH_REF__';
1.168     albertel 5729:   return $result;
                   5730: }
                   5731: 
                   5732: sub str2hash {
1.265     albertel 5733:     my ($string)=@_;
                   5734:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5735:     return %$hash;
                   5736: }
                   5737: 
                   5738: sub str2hashref {
1.168     albertel 5739:   my ($string) = @_;
1.265     albertel 5740: 
                   5741:   my %hash;
                   5742: 
                   5743:   if($string !~ /^__HASH_REF__/) {
                   5744:       if (! ($string eq '' || !defined($string))) {
                   5745: 	  $hash{'error'}='Not hash reference';
                   5746:       }
                   5747:       return (\%hash, $string);
                   5748:   }
                   5749: 
                   5750:   $string =~ s/^__HASH_REF__//;
                   5751: 
                   5752:   while($string !~ /^__END_HASH_REF__/) {
                   5753:       #key
                   5754:       my $key='';
                   5755:       if($string =~ /^__HASH_REF__/) {
                   5756:           ($key, $string)=&str2hashref($string);
                   5757:           if(defined($key->{'error'})) {
                   5758:               $hash{'error'}='Bad data';
                   5759:               return (\%hash, $string);
                   5760:           }
                   5761:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5762:           ($key, $string)=&str2arrayref($string);
                   5763:           if($key->[0] eq 'Array reference error') {
                   5764:               $hash{'error'}='Bad data';
                   5765:               return (\%hash, $string);
                   5766:           }
                   5767:       } else {
                   5768:           $string =~ s/^(.*?)=//;
1.267     albertel 5769: 	  $key=&unescape($1);
1.265     albertel 5770:       }
                   5771:       $string =~ s/^=//;
                   5772: 
                   5773:       #value
                   5774:       my $value='';
                   5775:       if($string =~ /^__HASH_REF__/) {
                   5776:           ($value, $string)=&str2hashref($string);
                   5777:           if(defined($value->{'error'})) {
                   5778:               $hash{'error'}='Bad data';
                   5779:               return (\%hash, $string);
                   5780:           }
                   5781:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5782:           ($value, $string)=&str2arrayref($string);
                   5783:           if($value->[0] eq 'Array reference error') {
                   5784:               $hash{'error'}='Bad data';
                   5785:               return (\%hash, $string);
                   5786:           }
                   5787:       } else {
                   5788: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5789:       }
                   5790:       $string =~ s/^&//;
                   5791: 
                   5792:       $hash{$key}=$value;
1.204     albertel 5793:   }
1.265     albertel 5794: 
                   5795:   $string =~ s/^__END_HASH_REF__//;
                   5796: 
                   5797:   return (\%hash, $string);
1.204     albertel 5798: }
                   5799: 
                   5800: sub str2array {
1.265     albertel 5801:     my ($string)=@_;
                   5802:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5803:     return @$array;
                   5804: }
                   5805: 
                   5806: sub str2arrayref {
1.204     albertel 5807:   my ($string) = @_;
1.265     albertel 5808:   my @array;
                   5809: 
                   5810:   if($string !~ /^__ARRAY_REF__/) {
                   5811:       if (! ($string eq '' || !defined($string))) {
                   5812: 	  $array[0]='Array reference error';
                   5813:       }
                   5814:       return (\@array, $string);
                   5815:   }
                   5816: 
                   5817:   $string =~ s/^__ARRAY_REF__//;
                   5818: 
                   5819:   while($string !~ /^__END_ARRAY_REF__/) {
                   5820:       my $value='';
                   5821:       if($string =~ /^__HASH_REF__/) {
                   5822:           ($value, $string)=&str2hashref($string);
                   5823:           if(defined($value->{'error'})) {
                   5824:               $array[0] ='Array reference error';
                   5825:               return (\@array, $string);
                   5826:           }
                   5827:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5828:           ($value, $string)=&str2arrayref($string);
                   5829:           if($value->[0] eq 'Array reference error') {
                   5830:               $array[0] ='Array reference error';
                   5831:               return (\@array, $string);
                   5832:           }
                   5833:       } else {
                   5834: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5835:       }
                   5836:       $string =~ s/^&//;
                   5837: 
                   5838:       push(@array, $value);
1.191     harris41 5839:   }
1.265     albertel 5840: 
                   5841:   $string =~ s/^__END_ARRAY_REF__//;
                   5842: 
                   5843:   return (\@array, $string);
1.168     albertel 5844: }
                   5845: 
1.167     albertel 5846: # -------------------------------------------------------------------Temp Store
                   5847: 
1.168     albertel 5848: sub tmpreset {
                   5849:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5850:   if (!$symb) {
                   5851:     $symb=&symbread();
1.620     albertel 5852:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5853:   }
                   5854:   $symb=escape($symb);
                   5855: 
1.620     albertel 5856:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5857:   $namespace=~s/\//\_/g;
                   5858:   $namespace=~s/\W//g;
                   5859: 
1.620     albertel 5860:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5861:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5862:   if ($domain eq 'public' && $stuname eq 'public') {
                   5863:       $stuname=$ENV{'REMOTE_ADDR'};
                   5864:   }
1.1117    foxr     5865:   my $path=LONCAPA::tempdir();
1.168     albertel 5866:   my %hash;
                   5867:   if (tie(%hash,'GDBM_File',
                   5868: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5869: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5870:     foreach my $key (keys(%hash)) {
1.180     albertel 5871:       if ($key=~ /:$symb/) {
1.168     albertel 5872: 	delete($hash{$key});
                   5873:       }
                   5874:     }
                   5875:   }
                   5876: }
                   5877: 
1.167     albertel 5878: sub tmpstore {
1.168     albertel 5879:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5880: 
                   5881:   if (!$symb) {
                   5882:     $symb=&symbread();
1.620     albertel 5883:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5884:   }
                   5885:   $symb=escape($symb);
                   5886: 
                   5887:   if (!$namespace) {
                   5888:     # I don't think we would ever want to store this for a course.
                   5889:     # it seems this will only be used if we don't have a course.
1.620     albertel 5890:     #$namespace=$env{'request.course.id'};
1.168     albertel 5891:     #if (!$namespace) {
1.620     albertel 5892:       $namespace=$env{'request.state'};
1.168     albertel 5893:     #}
                   5894:   }
                   5895:   $namespace=~s/\//\_/g;
                   5896:   $namespace=~s/\W//g;
1.620     albertel 5897:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5898:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5899:   if ($domain eq 'public' && $stuname eq 'public') {
                   5900:       $stuname=$ENV{'REMOTE_ADDR'};
                   5901:   }
1.168     albertel 5902:   my $now=time;
                   5903:   my %hash;
1.1117    foxr     5904:   my $path=LONCAPA::tempdir();
1.168     albertel 5905:   if (tie(%hash,'GDBM_File',
                   5906: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5907: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5908:     $hash{"version:$symb"}++;
                   5909:     my $version=$hash{"version:$symb"};
                   5910:     my $allkeys=''; 
                   5911:     foreach my $key (keys(%$storehash)) {
                   5912:       $allkeys.=$key.':';
1.591     albertel 5913:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5914:     }
                   5915:     $hash{"$version:$symb:timestamp"}=$now;
                   5916:     $allkeys.='timestamp';
                   5917:     $hash{"$version:keys:$symb"}=$allkeys;
                   5918:     if (untie(%hash)) {
                   5919:       return 'ok';
                   5920:     } else {
                   5921:       return "error:$!";
                   5922:     }
                   5923:   } else {
                   5924:     return "error:$!";
                   5925:   }
                   5926: }
1.167     albertel 5927: 
1.168     albertel 5928: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5929: 
1.168     albertel 5930: sub tmprestore {
                   5931:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5932: 
1.168     albertel 5933:   if (!$symb) {
                   5934:     $symb=&symbread();
1.620     albertel 5935:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5936:   }
                   5937:   $symb=escape($symb);
                   5938: 
1.620     albertel 5939:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5940: 
1.620     albertel 5941:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5942:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5943:   if ($domain eq 'public' && $stuname eq 'public') {
                   5944:       $stuname=$ENV{'REMOTE_ADDR'};
                   5945:   }
1.168     albertel 5946:   my %returnhash;
                   5947:   $namespace=~s/\//\_/g;
                   5948:   $namespace=~s/\W//g;
                   5949:   my %hash;
1.1117    foxr     5950:   my $path=LONCAPA::tempdir();
1.168     albertel 5951:   if (tie(%hash,'GDBM_File',
                   5952: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5953: 	  &GDBM_READER(),0640)) {
1.168     albertel 5954:     my $version=$hash{"version:$symb"};
                   5955:     $returnhash{'version'}=$version;
                   5956:     my $scope;
                   5957:     for ($scope=1;$scope<=$version;$scope++) {
                   5958:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5959:       my @keys=split(/:/,$vkeys);
                   5960:       my $key;
                   5961:       $returnhash{"$scope:keys"}=$vkeys;
                   5962:       foreach $key (@keys) {
1.591     albertel 5963: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5964: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5965:       }
                   5966:     }
1.168     albertel 5967:     if (!(untie(%hash))) {
                   5968:       return "error:$!";
                   5969:     }
                   5970:   } else {
                   5971:     return "error:$!";
                   5972:   }
                   5973:   return %returnhash;
1.167     albertel 5974: }
                   5975: 
1.9       www      5976: # ----------------------------------------------------------------------- Store
                   5977: 
                   5978: sub store {
1.1172.2.64  raeburn  5979:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5980:     my $home='';
                   5981: 
1.168     albertel 5982:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5983: 
1.213     www      5984:     $symb=&symbclean($symb);
1.122     albertel 5985:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5986: 
1.620     albertel 5987:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5988:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5989: 
                   5990:     &devalidate($symb,$stuname,$domain);
1.109     www      5991: 
                   5992:     $symb=escape($symb);
1.187     www      5993:     if (!$namespace) { 
1.620     albertel 5994:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5995:           return ''; 
                   5996:        } 
                   5997:     }
1.620     albertel 5998:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5999: 
                   6000:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6001:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6002: 
1.12      www      6003:     my $namevalue='';
1.800     albertel 6004:     foreach my $key (keys(%$storehash)) {
                   6005:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6006:     }
1.12      www      6007:     $namevalue=~s/\&$//;
1.187     www      6008:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6009:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6010: }
                   6011: 
1.47      www      6012: # -------------------------------------------------------------- Critical Store
                   6013: 
                   6014: sub cstore {
1.1172.2.64  raeburn  6015:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6016:     my $home='';
                   6017: 
1.168     albertel 6018:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6019: 
1.213     www      6020:     $symb=&symbclean($symb);
1.122     albertel 6021:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6022: 
1.620     albertel 6023:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6024:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6025: 
                   6026:     &devalidate($symb,$stuname,$domain);
1.109     www      6027: 
                   6028:     $symb=escape($symb);
1.187     www      6029:     if (!$namespace) { 
1.620     albertel 6030:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6031:           return ''; 
                   6032:        } 
                   6033:     }
1.620     albertel 6034:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6035: 
                   6036:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6037:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6038: 
1.47      www      6039:     my $namevalue='';
1.800     albertel 6040:     foreach my $key (keys(%$storehash)) {
                   6041:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6042:     }
1.47      www      6043:     $namevalue=~s/\&$//;
1.187     www      6044:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6045:     return critical
1.1172.2.64  raeburn  6046:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6047: }
                   6048: 
1.9       www      6049: # --------------------------------------------------------------------- Restore
                   6050: 
                   6051: sub restore {
1.124     www      6052:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6053:     my $home='';
                   6054: 
1.168     albertel 6055:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6056: 
1.122     albertel 6057:     if (!$symb) {
1.1172.2.26  raeburn  6058:         return if ($namespace eq 'courserequests');
                   6059:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6060:     } else {
1.1172.2.26  raeburn  6061:         unless ($namespace eq 'courserequests') {
                   6062:             $symb=&escape(&symbclean($symb));
                   6063:         }
1.122     albertel 6064:     }
1.188     www      6065:     if (!$namespace) { 
1.620     albertel 6066:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6067:           return ''; 
                   6068:        } 
                   6069:     }
1.620     albertel 6070:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6071:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6072:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6073:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6074: 
1.12      www      6075:     my %returnhash=();
1.800     albertel 6076:     foreach my $line (split(/\&/,$answer)) {
                   6077: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6078:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6079:     }
1.75      www      6080:     my $version;
                   6081:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6082:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6083:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6084:        }
1.75      www      6085:     }
1.13      www      6086:     return %returnhash;
1.34      www      6087: }
                   6088: 
                   6089: # ---------------------------------------------------------- Course Description
1.1118    foxr     6090: #
                   6091: #  
1.34      www      6092: 
                   6093: sub coursedescription {
1.731     albertel 6094:     my ($courseid,$args)=@_;
1.34      www      6095:     $courseid=~s/^\///;
1.49      www      6096:     $courseid=~s/\_/\//g;
1.34      www      6097:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6098:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6099:     my $normalid=$cdomain.'_'.$cnum;
                   6100:     # need to always cache even if we get errors otherwise we keep 
                   6101:     # trying and trying and trying to get the course description.
                   6102:     my %envhash=();
                   6103:     my %returnhash=();
1.731     albertel 6104:     
                   6105:     my $expiretime=600;
                   6106:     if ($env{'request.course.id'} eq $normalid) {
                   6107: 	$expiretime=120;
                   6108:     }
                   6109: 
                   6110:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6111:     if (!$args->{'freshen_cache'}
                   6112: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6113: 	foreach my $key (keys(%env)) {
                   6114: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6115: 	    my ($setting) = $1;
                   6116: 	    $returnhash{$setting} = $env{$key};
                   6117: 	}
                   6118: 	return %returnhash;
                   6119:     }
                   6120: 
1.1118    foxr     6121:     # get the data again
                   6122: 
1.731     albertel 6123:     if (!$args->{'one_time'}) {
                   6124: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6125:     }
1.811     albertel 6126: 
1.34      www      6127:     if ($chome ne 'no_host') {
1.302     albertel 6128:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6129:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6130: 	   my $username = $env{'user.name'}; # Defult username
                   6131: 	   if(defined $args->{'user'}) {
                   6132: 	       $username = $args->{'user'};
                   6133: 	   }
1.129     albertel 6134:            $returnhash{'home'}= $chome;
                   6135: 	   $returnhash{'domain'} = $cdomain;
                   6136: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6137:            if (!defined($returnhash{'type'})) {
                   6138:                $returnhash{'type'} = 'Course';
                   6139:            }
1.130     albertel 6140:            while (my ($name,$value) = each %returnhash) {
1.53      www      6141:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6142:            }
1.270     www      6143:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6144:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6145: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6146:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6147:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6148:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6149:        }
                   6150:     }
1.731     albertel 6151:     if (!$args->{'one_time'}) {
1.949     raeburn  6152: 	&appenv(\%envhash);
1.731     albertel 6153:     }
1.302     albertel 6154:     return %returnhash;
1.461     www      6155: }
                   6156: 
1.1080    raeburn  6157: sub update_released_required {
                   6158:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6159:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6160:         $cid = $env{'request.course.id'};
                   6161:         $cdom = $env{'course.'.$cid.'.domain'};
                   6162:         $cnum = $env{'course.'.$cid.'.num'};
                   6163:         $chome = $env{'course.'.$cid.'.home'};
                   6164:     }
                   6165:     if ($needsrelease) {
                   6166:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6167:         my $needsupdate;
                   6168:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6169:             $needsupdate = 1;
                   6170:         } else {
                   6171:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6172:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6173:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6174:                 $needsupdate = 1;
                   6175:             }
                   6176:         }
                   6177:         if ($needsupdate) {
                   6178:             my %needshash = (
                   6179:                              'internal.releaserequired' => $needsrelease,
                   6180:                             );
                   6181:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6182:             if ($putresult eq 'ok') {
                   6183:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6184:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6185:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6186:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6187:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6188:                 }
                   6189:             }
                   6190:         }
                   6191:     }
                   6192:     return;
                   6193: }
                   6194: 
1.461     www      6195: # -------------------------------------------------See if a user is privileged
                   6196: 
                   6197: sub privileged {
1.1172.2.23  raeburn  6198:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6199:     my $now = time;
1.1172.2.23  raeburn  6200:     my $roles;
                   6201:     if (ref($possroles) eq 'ARRAY') {
                   6202:         $roles = $possroles;
                   6203:     } else {
                   6204:         $roles = ['dc','su'];
                   6205:     }
                   6206:     if (ref($possdomains) eq 'ARRAY') {
                   6207:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6208:         foreach my $dom (@{$possdomains}) {
                   6209:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6210:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6211:                 foreach my $role (@{$roles}) {
                   6212:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6213:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6214:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6215:                             return 1 unless (($end && $end < $now) ||
                   6216:                                              ($start && $start > $now));
                   6217:                         }
                   6218:                     }
                   6219:                 }
                   6220:             }
                   6221:         }
                   6222:     } else {
                   6223:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6224:         my $now = time;
1.1170    droeschl 6225: 
1.1172.2.58  raeburn  6226:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6227:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6228:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6229:                 return 1 unless ($tend && $tend < $now)
                   6230:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6231:             }
1.1172.2.23  raeburn  6232:         }
                   6233:     }
1.461     www      6234:     return 0;
1.9       www      6235: }
1.1       albertel 6236: 
1.1172.2.23  raeburn  6237: sub privileged_by_domain {
                   6238:     my ($domains,$roles) = @_;
                   6239:     my %privileged = ();
                   6240:     my $cachetime = 60*60*24;
                   6241:     my $now = time;
                   6242:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6243:         return %privileged;
                   6244:     }
                   6245:     foreach my $dom (@{$domains}) {
                   6246:         next if (ref($privileged{$dom}) eq 'HASH');
                   6247:         my $needroles;
                   6248:         foreach my $role (@{$roles}) {
                   6249:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6250:             if (defined($cached)) {
                   6251:                 if (ref($result) eq 'HASH') {
                   6252:                     $privileged{$dom}{$role} = $result;
                   6253:                 }
                   6254:             } else {
                   6255:                 $needroles = 1;
                   6256:             }
                   6257:         }
                   6258:         if ($needroles) {
                   6259:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6260:             $privileged{$dom} = {};
                   6261:             foreach my $server (keys(%dompersonnel)) {
                   6262:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6263:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6264:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6265:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6266:                         next if ($end && $end < $now);
                   6267:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6268:                             $dompersonnel{$server}{$item};
                   6269:                     }
                   6270:                 }
                   6271:             }
                   6272:             if (ref($privileged{$dom}) eq 'HASH') {
                   6273:                 foreach my $role (@{$roles}) {
                   6274:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6275:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6276:                     } else {
                   6277:                         my %hash = ();
                   6278:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6279:                     }
                   6280:                 }
                   6281:             }
                   6282:         }
                   6283:     }
                   6284:     return %privileged;
                   6285: }
                   6286: 
1.103     harris41 6287: # -------------------------------------------------------- Get user privileges
1.11      www      6288: 
                   6289: sub rolesinit {
1.1169    droeschl 6290:     my ($domain, $username) = @_;
                   6291:     my %userroles = ('user.login.time' => time);
                   6292:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6293: 
                   6294:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6295:     # also, blocking can be triggered by an activating timer
                   6296:     # it's saved in the user's %env.
                   6297:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6298:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6299:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6300:         %timerintchk, %timerintenv);
                   6301: 
1.1162    raeburn  6302:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6303:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6304:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6305:     }
1.1169    droeschl 6306: 
1.1162    raeburn  6307:     foreach my $key (keys(%timerinterval)) {
                   6308:         my ($cid,$rest) = split(/\0/,$key);
                   6309:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6310:     }
1.1169    droeschl 6311: 
1.11      www      6312:     my %allroles=();
1.1162    raeburn  6313:     my %allgroups=();
1.11      www      6314: 
1.1172.2.58  raeburn  6315:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6316:         my $role = $rolesdump{$area};
                   6317:         $area =~ s/\_\w\w$//;
                   6318: 
                   6319:         my ($trole, $tend, $tstart, $group_privs);
                   6320: 
                   6321:         if ($role =~ /^cr/) {
                   6322:         # Custom role, defined by a user 
                   6323:         # e.g., user.role.cr/msu/smith/mynewrole
                   6324:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6325:                 $trole = $1;
                   6326:                 ($tend, $tstart) = split('_', $2);
                   6327:             } else {
                   6328:                 $trole = $role;
                   6329:             }
                   6330:         } elsif ($role =~ m|^gr/|) {
                   6331:         # Role of member in a group, defined within a course/community
                   6332:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6333:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6334:             next if $tstart eq '-1';
                   6335:             ($trole, $group_privs) = split(/\//, $trole);
                   6336:             $group_privs = &unescape($group_privs);
                   6337:         } else {
                   6338:         # Just a normal role, defined in roles.tab
                   6339:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6340:         }
                   6341: 
                   6342:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6343:                  $username);
                   6344:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6345: 
                   6346:         # role expired or not available yet?
                   6347:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6348:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6349: 
                   6350:         next if $area eq '' or $trole eq '';
                   6351: 
                   6352:         my $spec = "$trole.$area";
                   6353:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6354: 
                   6355:         if ($trole =~ /^cr\//) {
                   6356:         # Custom role, defined by a user
                   6357:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6358:         } elsif ($trole eq 'gr') {
                   6359:         # Role of a member in a group, defined within a course/community
                   6360:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6361:             next;
                   6362:         } else {
                   6363:         # Normal role, defined in roles.tab
                   6364:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6365:         }
                   6366: 
                   6367:         my $cid = $tdomain.'_'.$trest;
                   6368:         unless ($firstaccchk{$cid}) {
                   6369:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6370:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6371:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6372:                         $coursetimerstarts{$cid}{$item}; 
                   6373:                 }
                   6374:             }
                   6375:             $firstaccchk{$cid} = 1;
                   6376:         }
                   6377:         unless ($timerintchk{$cid}) {
                   6378:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6379:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6380:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6381:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6382:                 }
1.12      www      6383:             }
1.1169    droeschl 6384:             $timerintchk{$cid} = 1;
1.191     harris41 6385:         }
1.11      www      6386:     }
1.1169    droeschl 6387: 
1.1172.2.91  raeburn  6388:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6389:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6390:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6391:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6392: 
1.1162    raeburn  6393:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6394: }
                   6395: 
1.567     raeburn  6396: sub set_arearole {
1.1172.2.19  raeburn  6397:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6398:     unless ($nolog) {
1.567     raeburn  6399: # log the associated role with the area
1.1172.2.19  raeburn  6400:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6401:     }
1.743     albertel 6402:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6403: }
                   6404: 
                   6405: sub custom_roleprivs {
                   6406:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6407:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6408:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6409:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6410:         my ($rdummy,$roledef)=
                   6411:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6412:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6413:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6414:             if (defined($syspriv)) {
1.1043    raeburn  6415:                 if ($trest =~ /^$match_community$/) {
                   6416:                     $syspriv =~ s/bre\&S//; 
                   6417:                 }
1.567     raeburn  6418:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6419:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6420:             }
                   6421:             if ($tdomain ne '') {
                   6422:                 if (defined($dompriv)) {
                   6423:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6424:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6425:                 }
                   6426:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6427:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6428:                         my $rolename = $1;
                   6429:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6430:                     }
1.567     raeburn  6431:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6432:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6433:                 }
                   6434:             }
                   6435:         }
                   6436:     }
                   6437: }
                   6438: 
1.1172.2.89  raeburn  6439: sub course_adhocrole_privs {
                   6440:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6441:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6442:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6443:         my (%currprivs,%storeprivs);
                   6444:         foreach my $item (split(/:/,$coursepriv)) {
                   6445:             my ($priv,$restrict) = split(/\&/,$item);
                   6446:             $currprivs{$priv} = $restrict;
                   6447:         }
                   6448:         my (%possadd,%possremove,%full);
                   6449:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6450:             my ($priv,$restrict)=split(/\&/,$item);
                   6451:             $full{$priv} = $restrict;
                   6452:         }
                   6453:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6454:              next if ($item eq '');
                   6455:              my ($rule,$rest) = split(/=/,$item);
                   6456:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6457:              foreach my $priv (split(/:/,$rest)) {
                   6458:                  if ($priv ne '') {
                   6459:                      if ($rule eq 'off') {
                   6460:                          $possremove{$priv} = 1;
                   6461:                      } else {
                   6462:                          $possadd{$priv} = 1;
                   6463:                      }
                   6464:                  }
                   6465:              }
                   6466:          }
                   6467:          foreach my $priv (sort(keys(%full))) {
                   6468:              if (exists($currprivs{$priv})) {
                   6469:                  unless (exists($possremove{$priv})) {
                   6470:                      $storeprivs{$priv} = $currprivs{$priv};
                   6471:                  }
                   6472:              } elsif (exists($possadd{$priv})) {
                   6473:                  $storeprivs{$priv} = $full{$priv};
                   6474:              }
                   6475:          }
                   6476:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6477:      }
                   6478:      return $coursepriv;
                   6479: }
                   6480: 
1.678     raeburn  6481: sub group_roleprivs {
                   6482:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6483:     my $access = 1;
                   6484:     my $now = time;
                   6485:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6486:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6487:     if ($access) {
1.811     albertel 6488:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6489:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6490:     }
                   6491: }
1.567     raeburn  6492: 
                   6493: sub standard_roleprivs {
                   6494:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6495:     if (defined($pr{$trole.':s'})) {
                   6496:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6497:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6498:     }
                   6499:     if ($tdomain ne '') {
                   6500:         if (defined($pr{$trole.':d'})) {
                   6501:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6502:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6503:         }
                   6504:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6505:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6506:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6507:         }
                   6508:     }
                   6509: }
                   6510: 
                   6511: sub set_userprivs {
1.1064    raeburn  6512:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6513:     my $author=0;
                   6514:     my $adv=0;
1.1172.2.91  raeburn  6515:     my $rar=0;
1.678     raeburn  6516:     my %grouproles = ();
                   6517:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6518:         my @groupkeys; 
1.1000    raeburn  6519:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6520:             push(@groupkeys,$role);
                   6521:         }
                   6522:         if (ref($groups_roles) eq 'HASH') {
                   6523:             foreach my $key (keys(%{$groups_roles})) {
                   6524:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6525:                     push(@groupkeys,$key);
                   6526:                 }
                   6527:             }
                   6528:         }
                   6529:         if (@groupkeys > 0) {
                   6530:             foreach my $role (@groupkeys) {
                   6531:                 my ($trole,$area,$sec,$extendedarea);
                   6532:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6533:                     $trole = $1;
                   6534:                     $area = $2;
                   6535:                     $sec = $3;
                   6536:                     $extendedarea = $area.$sec;
                   6537:                     if (exists($$allgroups{$area})) {
                   6538:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6539:                             my $spec = $trole.'.'.$extendedarea;
                   6540:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6541:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6542:                         }
1.678     raeburn  6543:                     }
                   6544:                 }
                   6545:             }
                   6546:         }
                   6547:     }
1.800     albertel 6548:     foreach my $group (keys(%grouproles)) {
                   6549:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6550:     }
1.800     albertel 6551:     foreach my $role (keys(%{$allroles})) {
                   6552:         my %thesepriv;
1.941     raeburn  6553:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6554:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6555:             if ($item ne '') {
                   6556:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6557:                 if ($restrictions eq '') {
                   6558:                     $thesepriv{$privilege}='F';
                   6559:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6560:                     $thesepriv{$privilege}.=$restrictions;
                   6561:                 }
                   6562:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6563:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6564:             }
                   6565:         }
                   6566:         my $thesestr='';
1.1104    raeburn  6567:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6568: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6569: 	}
                   6570:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6571:     }
1.1172.2.91  raeburn  6572:     return ($author,$adv,$rar);
1.567     raeburn  6573: }
                   6574: 
1.994     raeburn  6575: sub role_status {
1.1104    raeburn  6576:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6577:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6578:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6579:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6580:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6581:             $$where = '/'.$two;
1.994     raeburn  6582:             $$trolecode=$$role.'.'.$$where;
                   6583:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6584:             $$tstatus='is';
1.1104    raeburn  6585:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6586:                 $$tstatus='future';
1.1034    raeburn  6587:                 if ($$tstart<$now) {
                   6588:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6589:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6590:                             my (%allroles,%allgroups,$group_privs,
                   6591:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6592:                             my %userroles = (
                   6593:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6594:                             );
1.1064    raeburn  6595:                             @rolecodes = ('cm'); 
1.1002    raeburn  6596:                             my $spec=$$role.'.'.$$where;
                   6597:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6598:                             if ($$role =~ /^cr\//) {
                   6599:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6600:                                 push(@rolecodes,'cr');
1.1002    raeburn  6601:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6602:                                 push(@rolecodes,$$role);
1.1002    raeburn  6603:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6604:                                                     $env{'user.name'});
1.1064    raeburn  6605:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6606:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6607:                                 $group_privs = &unescape($group_privs);
                   6608:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6609:                                 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  6610:                                 &get_groups_roles($tdomain,$trest,
                   6611:                                                   \%course_roles,\@rolecodes,
                   6612:                                                   \%groups_roles);
1.1002    raeburn  6613:                             } else {
1.1064    raeburn  6614:                                 push(@rolecodes,$$role);
1.1002    raeburn  6615:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6616:                             }
1.1172.2.91  raeburn  6617:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6618:                                                                    \%groups_roles);
1.1064    raeburn  6619:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6620:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6621:                         }
                   6622:                     }
1.1034    raeburn  6623:                     $$tstatus = 'is';
1.1002    raeburn  6624:                 }
1.994     raeburn  6625:             }
                   6626:             if ($$tend) {
1.1104    raeburn  6627:                 if ($$tend<$update) {
1.994     raeburn  6628:                     $$tstatus='expired';
                   6629:                 } elsif ($$tend<$now) {
                   6630:                     $$tstatus='will_not';
                   6631:                 }
                   6632:             }
                   6633:         }
                   6634:     }
                   6635: }
                   6636: 
1.1104    raeburn  6637: sub get_groups_roles {
                   6638:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6639:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6640:                   (ref($rolecodes) eq 'ARRAY') && 
                   6641:                   (ref($groups_roles) eq 'HASH')); 
                   6642:     if (keys(%{$cdom_courseroles}) > 0) {
                   6643:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6644:         if ($cdom ne '' && $cnum ne '') {
                   6645:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6646:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6647:                     my $crsrole = $1;
                   6648:                     my $crssec = $2;
                   6649:                     if ($crsrole =~ /^cr/) {
                   6650:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6651:                             push(@{$rolecodes},'cr');
                   6652:                         }
                   6653:                     } else {
                   6654:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6655:                             push(@{$rolecodes},$crsrole);
                   6656:                         }
                   6657:                     }
                   6658:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6659:                     if ($crssec ne '') {
                   6660:                         $rolekey .= "/$crssec";
                   6661:                     }
                   6662:                     $rolekey .= './';
                   6663:                     $groups_roles->{$rolekey} = $rolecodes;
                   6664:                 }
                   6665:             }
                   6666:         }
                   6667:     }
                   6668:     return;
                   6669: }
                   6670: 
                   6671: sub delete_env_groupprivs {
                   6672:     my ($where,$courseroles,$possroles) = @_;
                   6673:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6674:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6675:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6676:         %{$courseroles->{$udom}} =
                   6677:             &get_my_roles('','','userroles',['active'],
                   6678:                           $possroles,[$udom],1);
                   6679:     }
                   6680:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6681:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6682:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6683:             my $area = '/'.$cdom.'/'.$cnum;
                   6684:             my $privkey = "user.priv.$crsrole.$area";
                   6685:             if ($crssec ne '') {
                   6686:                 $privkey .= '/'.$crssec;
                   6687:             }
                   6688:             $privkey .= ".$area/$group";
                   6689:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6690:         }
                   6691:     }
                   6692:     return;
                   6693: }
                   6694: 
1.994     raeburn  6695: sub check_adhoc_privs {
1.1172.2.86  raeburn  6696:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6697:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6698:     if ($sec) {
                   6699:         $cckey .= '/'.$sec;
                   6700:     }
1.1172.2.9  raeburn  6701:     my $setprivs;
1.994     raeburn  6702:     if ($env{$cckey}) {
                   6703:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6704:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6705:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6706:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6707:             $setprivs = 1;
1.994     raeburn  6708:         }
                   6709:     } else {
1.1172.2.87  raeburn  6710:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6711:         $setprivs = 1;
1.994     raeburn  6712:     }
1.1172.2.9  raeburn  6713:     return $setprivs;
1.994     raeburn  6714: }
                   6715: 
                   6716: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6717: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6718:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6719:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6720:     if ($sec ne '') {
                   6721:         $area .= '/'.$sec;
                   6722:     }
1.994     raeburn  6723:     my $spec = $role.'.'.$area;
                   6724:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6725:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6726:     my %rolehash = ();
1.1172.2.89  raeburn  6727:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6728:         my $rolename = $1;
1.1172.2.84  raeburn  6729:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6730:         my %domdef = &get_domain_defaults($dcdom);
                   6731:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6732:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6733:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6734:             }
                   6735:         }
1.1172.2.84  raeburn  6736:     } else {
                   6737:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6738:     }
1.1172.2.91  raeburn  6739:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6740:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6741:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6742:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6743:         &appenv( {'request.role'        => $spec,
                   6744:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6745:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6746:                  }
                   6747:                );
                   6748:         my $tadv=0;
                   6749:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6750:         &appenv({'request.role.adv'    => $tadv});
                   6751:     }
1.994     raeburn  6752: }
                   6753: 
1.12      www      6754: # --------------------------------------------------------------- get interface
                   6755: 
                   6756: sub get {
1.131     albertel 6757:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6758:    my $items='';
1.800     albertel 6759:    foreach my $item (@$storearr) {
                   6760:        $items.=&escape($item).'&';
1.191     harris41 6761:    }
1.12      www      6762:    $items=~s/\&$//;
1.620     albertel 6763:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6764:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6765:    my $uhome=&homeserver($uname,$udomain);
                   6766: 
1.133     albertel 6767:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6768:    my @pairs=split(/\&/,$rep);
1.273     albertel 6769:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6770:      return @pairs;
                   6771:    }
1.15      www      6772:    my %returnhash=();
1.42      www      6773:    my $i=0;
1.800     albertel 6774:    foreach my $item (@$storearr) {
                   6775:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6776:       $i++;
1.191     harris41 6777:    }
1.15      www      6778:    return %returnhash;
1.27      www      6779: }
                   6780: 
                   6781: # --------------------------------------------------------------- del interface
                   6782: 
                   6783: sub del {
1.133     albertel 6784:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6785:    my $items='';
1.800     albertel 6786:    foreach my $item (@$storearr) {
                   6787:        $items.=&escape($item).'&';
1.191     harris41 6788:    }
1.984     neumanie 6789: 
1.27      www      6790:    $items=~s/\&$//;
1.620     albertel 6791:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6792:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6793:    my $uhome=&homeserver($uname,$udomain);
                   6794:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6795: }
                   6796: 
                   6797: # -------------------------------------------------------------- dump interface
                   6798: 
1.1172.2.22  raeburn  6799: sub unserialize {
                   6800:     my ($rep, $escapedkeys) = @_;
                   6801: 
                   6802:     return {} if $rep =~ /^error/;
                   6803: 
                   6804:     my %returnhash=();
                   6805:     foreach my $item (split(/\&/,$rep)) {
                   6806:         my ($key, $value) = split(/=/, $item, 2);
                   6807:         $key = unescape($key) unless $escapedkeys;
                   6808:         next if $key =~ /^error: 2 /;
                   6809:         $returnhash{$key} = &thaw_unescape($value);
                   6810:     }
                   6811:     return \%returnhash;
                   6812: }
                   6813: 
                   6814: # see Lond::dump_with_regexp
                   6815: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6816: sub dump {
1.1172.2.22  raeburn  6817:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6818:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6819:     if (!$uname) { $uname=$env{'user.name'}; }
                   6820:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6821: 
1.1172.2.55  raeburn  6822:     if ($regexp) {
                   6823:         $regexp=&escape($regexp);
                   6824:     } else {
                   6825:         $regexp='.';
                   6826:     }
1.1172.2.22  raeburn  6827:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6828:         # user is hosted on this machine
1.1172.2.55  raeburn  6829:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6830:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6831:         return %{&unserialize($reply, $escapedkeys)};
                   6832:     }
1.1166    raeburn  6833:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6834:     my @pairs=split(/\&/,$rep);
                   6835:     my %returnhash=();
1.1098    foxr     6836:     if (!($rep =~ /^error/ )) {
                   6837: 	foreach my $item (@pairs) {
                   6838: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6839:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6840: 	    next if ($key =~ /^error: 2 /);
                   6841: 	    $returnhash{$key}=&thaw_unescape($value);
                   6842: 	}
1.755     albertel 6843:     }
                   6844:     return %returnhash;
1.407     www      6845: }
                   6846: 
1.1098    foxr     6847: 
1.717     albertel 6848: # --------------------------------------------------------- dumpstore interface
                   6849: 
                   6850: sub dumpstore {
                   6851:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6852:    # same as dump but keys must be escaped. They may contain colon separated
                   6853:    # lists of values that may themself contain colons (e.g. symbs).
                   6854:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6855: }
                   6856: 
1.407     www      6857: # -------------------------------------------------------------- keys interface
                   6858: 
                   6859: sub getkeys {
                   6860:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6861:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6862:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6863:    my $uhome=&homeserver($uname,$udomain);
                   6864:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6865:    my @keyarray=();
1.800     albertel 6866:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6867:       next if ($key =~ /^error: 2 /);
1.800     albertel 6868:       push(@keyarray,&unescape($key));
1.407     www      6869:    }
                   6870:    return @keyarray;
1.318     matthew  6871: }
                   6872: 
1.319     matthew  6873: # --------------------------------------------------------------- currentdump
                   6874: sub currentdump {
1.328     matthew  6875:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6876:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6877:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6878:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6879:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6880:    my $rep;
                   6881: 
                   6882:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6883:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6884:                    $courseid)));
                   6885:    } else {
                   6886:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6887:    }
                   6888: 
1.318     matthew  6889:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6890:    #
1.318     matthew  6891:    my %returnhash=();
1.319     matthew  6892:    #
                   6893:    if ($rep eq "unknown_cmd") { 
                   6894:        # an old lond will not know currentdump
                   6895:        # Do a dump and make it look like a currentdump
1.822     albertel 6896:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6897:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6898:        my %hash = @tmp;
                   6899:        @tmp=();
1.424     matthew  6900:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6901:    } else {
                   6902:        my @pairs=split(/\&/,$rep);
1.800     albertel 6903:        foreach my $pair (@pairs) {
                   6904:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6905:            my ($symb,$param) = split(/:/,$key);
                   6906:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6907:                                                         &thaw_unescape($value);
1.319     matthew  6908:        }
1.191     harris41 6909:    }
1.12      www      6910:    return %returnhash;
1.424     matthew  6911: }
                   6912: 
                   6913: sub convert_dump_to_currentdump{
                   6914:     my %hash = %{shift()};
                   6915:     my %returnhash;
                   6916:     # Code ripped from lond, essentially.  The only difference
                   6917:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6918:     # we might run in to problems with parameter names =~ /^v\./
                   6919:     while (my ($key,$value) = each(%hash)) {
                   6920:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6921: 	$symb  = &unescape($symb);
                   6922: 	$param = &unescape($param);
1.424     matthew  6923:         next if ($v eq 'version' || $symb eq 'keys');
                   6924:         next if (exists($returnhash{$symb}) &&
                   6925:                  exists($returnhash{$symb}->{$param}) &&
                   6926:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6927:         $returnhash{$symb}->{$param}=$value;
                   6928:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6929:     }
                   6930:     #
                   6931:     # Remove all of the keys in the hashes which keep track of
                   6932:     # the version of the parameter.
                   6933:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6934:         # use a foreach because we are going to delete from the hash.
                   6935:         foreach my $key (keys(%$param_hash)) {
                   6936:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6937:         }
                   6938:     }
                   6939:     return \%returnhash;
1.12      www      6940: }
                   6941: 
1.627     albertel 6942: # ------------------------------------------------------ critical inc interface
                   6943: 
                   6944: sub cinc {
                   6945:     return &inc(@_,'critical');
                   6946: }
                   6947: 
1.449     matthew  6948: # --------------------------------------------------------------- inc interface
                   6949: 
                   6950: sub inc {
1.627     albertel 6951:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6952:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6953:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6954:     my $uhome=&homeserver($uname,$udomain);
                   6955:     my $items='';
                   6956:     if (! ref($store)) {
                   6957:         # got a single value, so use that instead
                   6958:         $items = &escape($store).'=&';
                   6959:     } elsif (ref($store) eq 'SCALAR') {
                   6960:         $items = &escape($$store).'=&';        
                   6961:     } elsif (ref($store) eq 'ARRAY') {
                   6962:         $items = join('=&',map {&escape($_);} @{$store});
                   6963:     } elsif (ref($store) eq 'HASH') {
                   6964:         while (my($key,$value) = each(%{$store})) {
                   6965:             $items.= &escape($key).'='.&escape($value).'&';
                   6966:         }
                   6967:     }
                   6968:     $items=~s/\&$//;
1.627     albertel 6969:     if ($critical) {
                   6970: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6971:     } else {
                   6972: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6973:     }
1.449     matthew  6974: }
                   6975: 
1.12      www      6976: # --------------------------------------------------------------- put interface
                   6977: 
                   6978: sub put {
1.134     albertel 6979:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6980:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6981:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6982:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6983:    my $items='';
1.800     albertel 6984:    foreach my $item (keys(%$storehash)) {
                   6985:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6986:    }
1.12      www      6987:    $items=~s/\&$//;
1.134     albertel 6988:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6989: }
                   6990: 
1.631     albertel 6991: # ------------------------------------------------------------ newput interface
                   6992: 
                   6993: sub newput {
                   6994:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6995:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6996:    if (!$uname) { $uname=$env{'user.name'}; }
                   6997:    my $uhome=&homeserver($uname,$udomain);
                   6998:    my $items='';
                   6999:    foreach my $key (keys(%$storehash)) {
                   7000:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7001:    }
                   7002:    $items=~s/\&$//;
                   7003:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7004: }
                   7005: 
                   7006: # ---------------------------------------------------------  putstore interface
                   7007: 
1.524     raeburn  7008: sub putstore {
1.1172.2.59  raeburn  7009:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7010:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7011:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7012:    my $uhome=&homeserver($uname,$udomain);
                   7013:    my $items='';
1.715     albertel 7014:    foreach my $key (keys(%$storehash)) {
                   7015:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7016:    }
1.715     albertel 7017:    $items=~s/\&$//;
1.716     albertel 7018:    my $esc_symb=&escape($symb);
                   7019:    my $esc_v=&escape($version);
1.715     albertel 7020:    my $reply =
1.716     albertel 7021:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7022: 	      $uhome);
1.1172.2.59  raeburn  7023:    if (($tolog) && ($reply eq 'ok')) {
                   7024:        my $namevalue='';
                   7025:        foreach my $key (keys(%{$storehash})) {
                   7026:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7027:        }
1.1172.2.134  raeburn  7028:        my $ip = &get_requestor_ip();
1.1172.2.135! raeburn  7029:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7030:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7031:                      '&version='.$esc_v.
                   7032:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7033:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7034:    }
1.715     albertel 7035:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7036:        # gfall back to way things use to be done
1.715     albertel 7037:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7038: 			    $uname);
1.524     raeburn  7039:    }
1.715     albertel 7040:    return $reply;
                   7041: }
                   7042: 
                   7043: sub old_putstore {
1.716     albertel 7044:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7045:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7046:     if (!$uname) { $uname=$env{'user.name'}; }
                   7047:     my $uhome=&homeserver($uname,$udomain);
                   7048:     my %newstorehash;
1.800     albertel 7049:     foreach my $item (keys(%$storehash)) {
                   7050: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7051: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7052:     }
                   7053:     my $items='';
                   7054:     my %allitems = ();
1.800     albertel 7055:     foreach my $item (keys(%newstorehash)) {
                   7056: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7057: 	    my $key = $1.':keys:'.$2;
                   7058: 	    $allitems{$key} .= $3.':';
                   7059: 	}
1.800     albertel 7060: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7061:     }
1.800     albertel 7062:     foreach my $item (keys(%allitems)) {
                   7063: 	$allitems{$item} =~ s/\:$//;
                   7064: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7065:     }
                   7066:     $items=~s/\&$//;
                   7067:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7068: }
                   7069: 
1.47      www      7070: # ------------------------------------------------------ critical put interface
                   7071: 
                   7072: sub cput {
1.134     albertel 7073:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7074:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7075:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7076:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7077:    my $items='';
1.800     albertel 7078:    foreach my $item (keys(%$storehash)) {
                   7079:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7080:    }
1.47      www      7081:    $items=~s/\&$//;
1.134     albertel 7082:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7083: }
                   7084: 
                   7085: # -------------------------------------------------------------- eget interface
                   7086: 
                   7087: sub eget {
1.133     albertel 7088:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7089:    my $items='';
1.800     albertel 7090:    foreach my $item (@$storearr) {
                   7091:        $items.=&escape($item).'&';
1.191     harris41 7092:    }
1.12      www      7093:    $items=~s/\&$//;
1.620     albertel 7094:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7095:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7096:    my $uhome=&homeserver($uname,$udomain);
                   7097:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7098:    my @pairs=split(/\&/,$rep);
                   7099:    my %returnhash=();
1.42      www      7100:    my $i=0;
1.800     albertel 7101:    foreach my $item (@$storearr) {
                   7102:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7103:       $i++;
1.191     harris41 7104:    }
1.12      www      7105:    return %returnhash;
                   7106: }
                   7107: 
1.667     albertel 7108: # ------------------------------------------------------------ tmpput interface
                   7109: sub tmpput {
1.802     raeburn  7110:     my ($storehash,$server,$context)=@_;
1.667     albertel 7111:     my $items='';
1.800     albertel 7112:     foreach my $item (keys(%$storehash)) {
                   7113: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7114:     }
                   7115:     $items=~s/\&$//;
1.802     raeburn  7116:     if (defined($context)) {
                   7117:         $items .= ':'.&escape($context);
                   7118:     }
1.667     albertel 7119:     return &reply("tmpput:$items",$server);
                   7120: }
                   7121: 
                   7122: # ------------------------------------------------------------ tmpget interface
                   7123: sub tmpget {
1.688     albertel 7124:     my ($token,$server)=@_;
                   7125:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7126:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7127:     my %returnhash;
1.1172.2.85  raeburn  7128:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7129:         return %returnhash;
                   7130:     }
1.667     albertel 7131:     foreach my $item (split(/\&/,$rep)) {
                   7132: 	my ($key,$value)=split(/=/,$item);
                   7133: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7134:     }
                   7135:     return %returnhash;
                   7136: }
                   7137: 
1.1113    raeburn  7138: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7139: sub tmpdel {
                   7140:     my ($token,$server)=@_;
                   7141:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7142:     return &reply("tmpdel:$token",$server);
                   7143: }
                   7144: 
1.1172.2.13  raeburn  7145: # ------------------------------------------------------------ get_timebased_id
                   7146: 
                   7147: sub get_timebased_id {
                   7148:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7149:         $maxtries) = @_;
                   7150:     my ($newid,$error,$dellock);
                   7151:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7152:         return ('','ok','invalid call to get suffix');
                   7153:     }
                   7154: 
                   7155: # set defaults for any optional args for which values were not supplied
                   7156:     if ($who eq '') {
                   7157:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7158:     }
                   7159:     if (!$locktries) {
                   7160:         $locktries = 3;
                   7161:     }
                   7162:     if (!$maxtries) {
                   7163:         $maxtries = 10;
                   7164:     }
                   7165: 
                   7166:     if (($cdom eq '') || ($cnum eq '')) {
                   7167:         if ($env{'request.course.id'}) {
                   7168:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7169:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7170:         }
                   7171:         if (($cdom eq '') || ($cnum eq '')) {
                   7172:             return ('','ok','call to get suffix not in course context');
                   7173:         }
                   7174:     }
                   7175: 
                   7176: # construct locking item
                   7177:     my $lockhash = {
                   7178:                       $prefix."\0".'locked_'.$keyid => $who,
                   7179:                    };
                   7180:     my $tries = 0;
                   7181: 
                   7182: # attempt to get lock on nohist_$namespace file
                   7183:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7184:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7185:         $tries ++;
                   7186:         sleep 1;
                   7187:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7188:     }
                   7189: 
                   7190: # attempt to get unique identifier, based on current timestamp
                   7191:     if ($gotlock eq 'ok') {
                   7192:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7193:         my $id = time;
                   7194:         $newid = $id;
1.1172.2.56  raeburn  7195:         if ($idtype eq 'addcode') {
                   7196:             $newid .= &sixnum_code();
                   7197:         }
1.1172.2.13  raeburn  7198:         my $idtries = 0;
                   7199:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7200:             if ($idtype eq 'concat') {
                   7201:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7202:             } elsif ($idtype eq 'addcode') {
                   7203:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7204:             } else {
                   7205:                 $newid ++;
                   7206:             }
                   7207:             $idtries ++;
                   7208:         }
                   7209:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7210:             my %new_item =  (
                   7211:                               $prefix."\0".$newid => $who,
                   7212:                             );
                   7213:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7214:                                                  $cdom,$cnum);
                   7215:             if ($putresult ne 'ok') {
                   7216:                 undef($newid);
                   7217:                 $error = 'error saving new item: '.$putresult;
                   7218:             }
                   7219:         } else {
1.1172.2.56  raeburn  7220:              undef($newid);
1.1172.2.13  raeburn  7221:              $error = ('error: no unique suffix available for the new item ');
                   7222:         }
                   7223: #  remove lock
                   7224:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7225:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7226:     } else {
                   7227:         $error = "error: could not obtain lockfile\n";
                   7228:         $dellock = 'ok';
1.1172.2.58  raeburn  7229:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7230:             $dellock = 'nolock';
                   7231:         }
1.1172.2.13  raeburn  7232:     }
                   7233:     return ($newid,$dellock,$error);
                   7234: }
                   7235: 
1.1172.2.56  raeburn  7236: sub sixnum_code {
                   7237:     my $code;
                   7238:     for (0..6) {
                   7239:         $code .= int( rand(9) );
                   7240:     }
                   7241:     return $code;
                   7242: }
                   7243: 
1.765     albertel 7244: # -------------------------------------------------- portfolio access checking
                   7245: 
                   7246: sub portfolio_access {
1.1172.2.77  raeburn  7247:     my ($requrl,$clientip) = @_;
1.765     albertel 7248:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7249:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7250:     if ($result) {
                   7251:         my %setters;
                   7252:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7253:             my ($startblock,$endblock) =
                   7254:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7255:             if ($startblock && $endblock) {
                   7256:                 return 'B';
                   7257:             }
                   7258:         } else {
                   7259:             my ($startblock,$endblock) =
                   7260:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7261:             if ($startblock && $endblock) {
                   7262:                 return 'B';
                   7263:             }
                   7264:         }
                   7265:     }
1.765     albertel 7266:     if ($result eq 'ok') {
1.766     albertel 7267:        return 'F';
1.765     albertel 7268:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7269:        return 'A';
1.765     albertel 7270:     }
1.766     albertel 7271:     return '';
1.765     albertel 7272: }
                   7273: 
                   7274: sub get_portfolio_access {
1.1172.2.77  raeburn  7275:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7276: 
                   7277:     if (!ref($access_hash)) {
                   7278: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7279: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7280: 						   $file_name);
                   7281: 	$access_hash = $access_controls{$file_name};
                   7282:     }
                   7283: 
1.1172.2.77  raeburn  7284:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7285:     my $now = time;
                   7286:     if (ref($access_hash) eq 'HASH') {
                   7287:         foreach my $key (keys(%{$access_hash})) {
                   7288:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7289:             if ($start > $now) {
                   7290:                 next;
                   7291:             }
                   7292:             if ($end && $end<$now) {
                   7293:                 next;
                   7294:             }
                   7295:             if ($scope eq 'public') {
                   7296:                 $public = $key;
                   7297:                 last;
                   7298:             } elsif ($scope eq 'guest') {
                   7299:                 $guest = $key;
                   7300:             } elsif ($scope eq 'domains') {
                   7301:                 push(@domains,$key);
                   7302:             } elsif ($scope eq 'users') {
                   7303:                 push(@users,$key);
                   7304:             } elsif ($scope eq 'course') {
                   7305:                 push(@courses,$key);
                   7306:             } elsif ($scope eq 'group') {
                   7307:                 push(@groups,$key);
1.1172.2.77  raeburn  7308:             } elsif ($scope eq 'ip') {
                   7309:                 push(@ips,$key);
1.765     albertel 7310:             }
                   7311:         }
                   7312:         if ($public) {
                   7313:             return 'ok';
1.1172.2.77  raeburn  7314:         } elsif (@ips > 0) {
                   7315:             my $allowed;
                   7316:             foreach my $ipkey (@ips) {
                   7317:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7318:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7319:                         $allowed = 1;
                   7320:                         last;
                   7321:                     }
                   7322:                 }
                   7323:             }
                   7324:             if ($allowed) {
                   7325:                 return 'ok';
                   7326:             }
1.765     albertel 7327:         }
                   7328:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7329:             if ($guest) {
                   7330:                 return $guest;
                   7331:             }
                   7332:         } else {
                   7333:             if (@domains > 0) {
                   7334:                 foreach my $domkey (@domains) {
                   7335:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7336:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7337:                             return 'ok';
                   7338:                         }
                   7339:                     }
                   7340:                 }
                   7341:             }
                   7342:             if (@users > 0) {
                   7343:                 foreach my $userkey (@users) {
1.865     raeburn  7344:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7345:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7346:                             if (ref($item) eq 'HASH') {
                   7347:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7348:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7349:                                     return 'ok';
                   7350:                                 }
                   7351:                             }
                   7352:                         }
                   7353:                     } 
1.765     albertel 7354:                 }
                   7355:             }
                   7356:             my %roleshash;
                   7357:             my @courses_and_groups = @courses;
                   7358:             push(@courses_and_groups,@groups); 
                   7359:             if (@courses_and_groups > 0) {
                   7360:                 my (%allgroups,%allroles); 
                   7361:                 my ($start,$end,$role,$sec,$group);
                   7362:                 foreach my $envkey (%env) {
1.1060    raeburn  7363:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7364:                         my $cid = $2.'_'.$3; 
                   7365:                         if ($1 eq 'gr') {
                   7366:                             $group = $4;
                   7367:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7368:                         } else {
                   7369:                             if ($4 eq '') {
                   7370:                                 $sec = 'none';
                   7371:                             } else {
                   7372:                                 $sec = $4;
                   7373:                             }
                   7374:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7375:                         }
1.811     albertel 7376:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7377:                         my $cid = $2.'_'.$3;
                   7378:                         if ($4 eq '') {
                   7379:                             $sec = 'none';
                   7380:                         } else {
                   7381:                             $sec = $4;
                   7382:                         }
                   7383:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7384:                     }
                   7385:                 }
                   7386:                 if (keys(%allroles) == 0) {
                   7387:                     return;
                   7388:                 }
                   7389:                 foreach my $key (@courses_and_groups) {
                   7390:                     my %content = %{$$access_hash{$key}};
                   7391:                     my $cnum = $content{'number'};
                   7392:                     my $cdom = $content{'domain'};
                   7393:                     my $cid = $cdom.'_'.$cnum;
                   7394:                     if (!exists($allroles{$cid})) {
                   7395:                         next;
                   7396:                     }    
                   7397:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7398:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7399:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7400:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7401:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7402:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7403:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7404:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7405:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7406:                                         if (grep/^all$/,@sections) {
                   7407:                                             return 'ok';
                   7408:                                         } else {
                   7409:                                             if (grep/^$sec$/,@sections) {
                   7410:                                                 return 'ok';
                   7411:                                             }
                   7412:                                         }
                   7413:                                     }
                   7414:                                 }
                   7415:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7416:                                     if (grep/^none$/,@groups) {
                   7417:                                         return 'ok';
                   7418:                                     }
                   7419:                                 } else {
                   7420:                                     if (grep/^all$/,@groups) {
                   7421:                                         return 'ok';
                   7422:                                     } 
                   7423:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7424:                                         if (grep/^$group$/,@groups) {
                   7425:                                             return 'ok';
                   7426:                                         }
                   7427:                                     }
                   7428:                                 } 
                   7429:                             }
                   7430:                         }
                   7431:                     }
                   7432:                 }
                   7433:             }
                   7434:             if ($guest) {
                   7435:                 return $guest;
                   7436:             }
                   7437:         }
                   7438:     }
                   7439:     return;
                   7440: }
                   7441: 
                   7442: sub course_group_datechecker {
                   7443:     my ($dates,$now,$status) = @_;
                   7444:     my ($start,$end) = split(/\./,$dates);
                   7445:     if (!$start && !$end) {
                   7446:         return 'ok';
                   7447:     }
                   7448:     if (grep/^active$/,@{$status}) {
                   7449:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7450:             return 'ok';
                   7451:         }
                   7452:     }
                   7453:     if (grep/^previous$/,@{$status}) {
                   7454:         if ($end > $now ) {
                   7455:             return 'ok';
                   7456:         }
                   7457:     }
                   7458:     if (grep/^future$/,@{$status}) {
                   7459:         if ($start > $now) {
                   7460:             return 'ok';
                   7461:         }
                   7462:     }
                   7463:     return; 
                   7464: }
                   7465: 
                   7466: sub parse_portfolio_url {
                   7467:     my ($url) = @_;
                   7468: 
                   7469:     my ($type,$udom,$unum,$group,$file_name);
                   7470:     
1.823     albertel 7471:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7472: 	$type = 1;
                   7473:         $udom = $1;
                   7474:         $unum = $2;
                   7475:         $file_name = $3;
1.823     albertel 7476:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7477: 	$type = 2;
                   7478:         $udom = $1;
                   7479:         $unum = $2;
                   7480:         $group = $3;
                   7481:         $file_name = $3.'/'.$4;
                   7482:     }
                   7483:     if (wantarray) {
                   7484: 	return ($type,$udom,$unum,$file_name,$group);
                   7485:     }
                   7486:     return $type;
                   7487: }
                   7488: 
                   7489: sub is_portfolio_url {
                   7490:     my ($url) = @_;
                   7491:     return scalar(&parse_portfolio_url($url));
                   7492: }
                   7493: 
1.798     raeburn  7494: sub is_portfolio_file {
                   7495:     my ($file) = @_;
1.820     raeburn  7496:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7497:         return 1;
                   7498:     }
                   7499:     return;
                   7500: }
                   7501: 
1.976     raeburn  7502: sub usertools_access {
1.1084    raeburn  7503:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7504:     my ($access,%tools);
                   7505:     if ($context eq '') {
                   7506:         $context = 'tools';
                   7507:     }
                   7508:     if ($context eq 'requestcourses') {
                   7509:         %tools = (
                   7510:                       official   => 1,
                   7511:                       unofficial => 1,
1.1006    raeburn  7512:                       community  => 1,
1.1172.2.37  raeburn  7513:                       textbook   => 1,
1.985     raeburn  7514:                  );
1.1172.2.9  raeburn  7515:     } elsif ($context eq 'requestauthor') {
                   7516:         %tools = (
                   7517:                       requestauthor => 1,
                   7518:                  );
1.985     raeburn  7519:     } else {
                   7520:         %tools = (
                   7521:                       aboutme   => 1,
                   7522:                       blog      => 1,
1.1172.2.6  raeburn  7523:                       webdav    => 1,
1.985     raeburn  7524:                       portfolio => 1,
                   7525:                  );
                   7526:     }
1.976     raeburn  7527:     return if (!defined($tools{$tool}));
                   7528: 
1.1172.2.35  raeburn  7529:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7530:         $udom = $env{'user.domain'};
                   7531:         $uname = $env{'user.name'};
                   7532:     }
                   7533: 
1.978     raeburn  7534:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7535:         if ($action ne 'reload') {
1.985     raeburn  7536:             if ($context eq 'requestcourses') {
                   7537:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7538:             } elsif ($context eq 'requestauthor') {
                   7539:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7540:             } else {
                   7541:                 return $env{'environment.availabletools.'.$tool};
                   7542:             }
                   7543:         }
1.976     raeburn  7544:     }
                   7545: 
1.1172.2.9  raeburn  7546:     my ($toolstatus,$inststatus,$envkey);
                   7547:     if ($context eq 'requestauthor') {
                   7548:         $envkey = $context;
                   7549:     } else {
                   7550:         $envkey = $context.'.'.$tool;
                   7551:     }
1.976     raeburn  7552: 
1.985     raeburn  7553:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7554:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7555:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7556:         $inststatus = $env{'environment.inststatus'};
                   7557:     } else {
1.1084    raeburn  7558:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7559:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7560:             $inststatus = $userenvref->{'inststatus'};
                   7561:         } else {
1.1172.2.9  raeburn  7562:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7563:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7564:             $inststatus = $userenv{'inststatus'};
                   7565:         }
1.976     raeburn  7566:     }
                   7567: 
                   7568:     if ($toolstatus ne '') {
                   7569:         if ($toolstatus) {
                   7570:             $access = 1;
                   7571:         } else {
                   7572:             $access = 0;
                   7573:         }
                   7574:         return $access;
                   7575:     }
                   7576: 
1.1084    raeburn  7577:     my ($is_adv,%domdef);
                   7578:     if (ref($is_advref) eq 'HASH') {
                   7579:         $is_adv = $is_advref->{'is_adv'};
                   7580:     } else {
                   7581:         $is_adv = &is_advanced_user($udom,$uname);
                   7582:     }
                   7583:     if (ref($domdefref) eq 'HASH') {
                   7584:         %domdef = %{$domdefref};
                   7585:     } else {
                   7586:         %domdef = &get_domain_defaults($udom);
                   7587:     }
1.976     raeburn  7588:     if (ref($domdef{$tool}) eq 'HASH') {
                   7589:         if ($is_adv) {
                   7590:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7591:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7592:                     $access = 1;
                   7593:                 } else {
                   7594:                     $access = 0;
                   7595:                 }
                   7596:                 return $access;
                   7597:             }
                   7598:         }
                   7599:         if ($inststatus ne '') {
                   7600:             my ($hasaccess,$hasnoaccess);
                   7601:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7602:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7603:                     if ($domdef{$tool}{$affiliation}) {
                   7604:                         $hasaccess = 1;
                   7605:                     } else {
                   7606:                         $hasnoaccess = 1;
                   7607:                     }
                   7608:                 }
                   7609:             }
                   7610:             if ($hasaccess || $hasnoaccess) {
                   7611:                 if ($hasaccess) {
                   7612:                     $access = 1;
                   7613:                 } elsif ($hasnoaccess) {
                   7614:                     $access = 0; 
                   7615:                 }
                   7616:                 return $access;
                   7617:             }
                   7618:         } else {
                   7619:             if ($domdef{$tool}{'default'} ne '') {
                   7620:                 if ($domdef{$tool}{'default'}) {
                   7621:                     $access = 1;
                   7622:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7623:                     $access = 0;
                   7624:                 }
                   7625:                 return $access;
                   7626:             }
                   7627:         }
                   7628:     } else {
1.1172.2.6  raeburn  7629:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7630:             $access = 1;
                   7631:         } else {
                   7632:             $access = 0;
                   7633:         }
1.976     raeburn  7634:         return $access;
                   7635:     }
                   7636: }
                   7637: 
1.1050    raeburn  7638: sub is_course_owner {
                   7639:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7640:     if (($udom eq '') || ($uname eq '')) {
                   7641:         $udom = $env{'user.domain'};
                   7642:         $uname = $env{'user.name'};
                   7643:     }
                   7644:     unless (($udom eq '') || ($uname eq '')) {
                   7645:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7646:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7647:                 return 1;
                   7648:             } else {
                   7649:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7650:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7651:                     return 1;
                   7652:                 }
                   7653:             }
                   7654:         }
                   7655:     }
                   7656:     return;
                   7657: }
                   7658: 
1.976     raeburn  7659: sub is_advanced_user {
                   7660:     my ($udom,$uname) = @_;
1.1085    raeburn  7661:     if ($udom ne '' && $uname ne '') {
                   7662:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7663:             if (wantarray) {
                   7664:                 return ($env{'user.adv'},$env{'user.author'});
                   7665:             } else {
                   7666:                 return $env{'user.adv'};
                   7667:             }
1.1085    raeburn  7668:         }
                   7669:     }
1.976     raeburn  7670:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7671:     my %allroles;
1.1128    raeburn  7672:     my ($is_adv,$is_author);
1.976     raeburn  7673:     foreach my $role (keys(%roleshash)) {
                   7674:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7675:         my $area = '/'.$tdomain.'/'.$trest;
                   7676:         if ($sec ne '') {
                   7677:             $area .= '/'.$sec;
                   7678:         }
                   7679:         if (($area ne '') && ($trole ne '')) {
                   7680:             my $spec=$trole.'.'.$area;
                   7681:             if ($trole =~ /^cr\//) {
                   7682:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7683:             } elsif ($trole ne 'gr') {
                   7684:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7685:             }
1.1128    raeburn  7686:             if ($trole eq 'au') {
                   7687:                 $is_author = 1;
                   7688:             }
1.976     raeburn  7689:         }
                   7690:     }
                   7691:     foreach my $role (keys(%allroles)) {
                   7692:         last if ($is_adv);
                   7693:         foreach my $item (split(/:/,$allroles{$role})) {
                   7694:             if ($item ne '') {
                   7695:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7696:                 if ($privilege eq 'adv') {
                   7697:                     $is_adv = 1;
                   7698:                     last;
                   7699:                 }
                   7700:             }
                   7701:         }
                   7702:     }
1.1128    raeburn  7703:     if (wantarray) {
                   7704:         return ($is_adv,$is_author);
                   7705:     }
1.976     raeburn  7706:     return $is_adv;
                   7707: }
1.798     raeburn  7708: 
1.1035    raeburn  7709: sub check_can_request {
1.1036    raeburn  7710:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7711:     my $canreq = 0;
                   7712:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7713:     my @options = ('approval','validate','autolimit');
                   7714:     my $optregex = join('|',@options);
                   7715:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7716:         foreach my $type (@{$types}) {
                   7717:             if (&usertools_access($env{'user.name'},
                   7718:                                   $env{'user.domain'},
                   7719:                                   $type,undef,'requestcourses')) {
                   7720:                 $canreq ++;
1.1036    raeburn  7721:                 if (ref($request_domains) eq 'HASH') {
                   7722:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7723:                 }
1.1035    raeburn  7724:                 if ($dom eq $env{'user.domain'}) {
                   7725:                     $can_request->{$type} = 1;
                   7726:                 }
                   7727:             }
                   7728:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7729:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7730:                 if (@curr > 0) {
1.1036    raeburn  7731:                     foreach my $item (@curr) {
                   7732:                         if (ref($request_domains) eq 'HASH') {
                   7733:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7734:                             if ($otherdom ne '') {
                   7735:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7736:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7737:                                         push(@{$request_domains->{$type}},$otherdom);
                   7738:                                     }
                   7739:                                 } else {
                   7740:                                     push(@{$request_domains->{$type}},$otherdom);
                   7741:                                 }
                   7742:                             }
                   7743:                         }
                   7744:                     }
                   7745:                     unless($dom eq $env{'user.domain'}) {
                   7746:                         $canreq ++;
1.1035    raeburn  7747:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7748:                             $can_request->{$type} = 1;
                   7749:                         }
                   7750:                     }
                   7751:                 }
                   7752:             }
                   7753:         }
                   7754:     }
                   7755:     return $canreq;
                   7756: }
                   7757: 
1.341     www      7758: # ---------------------------------------------- Custom access rule evaluation
                   7759: 
                   7760: sub customaccess {
                   7761:     my ($priv,$uri)=@_;
1.807     albertel 7762:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7763:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7764:     $udom = &LONCAPA::clean_domain($udom);
                   7765:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7766:     my $access=0;
1.800     albertel 7767:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7768: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7769: 	if ($type eq 'user') {
                   7770: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7771: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7772: 		if ($tdom) {
                   7773: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7774: 		}
1.896     albertel 7775: 		if ($tuname) {
                   7776: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7777: 		}
                   7778: 		$access=($effect eq 'allow');
                   7779: 		last;
                   7780: 	    }
                   7781: 	} else {
                   7782: 	    if ($role) {
                   7783: 		if ($role ne $urole) { next; }
                   7784: 	    }
                   7785: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7786: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7787: 		if ($tdom) {
                   7788: 		    if ($tdom ne $udom) { next; }
                   7789: 		}
                   7790: 		if ($tcrs) {
                   7791: 		    if ($tcrs ne $ucrs) { next; }
                   7792: 		}
                   7793: 		if ($tsec) {
                   7794: 		    if ($tsec ne $usec) { next; }
                   7795: 		}
                   7796: 		$access=($effect eq 'allow');
                   7797: 		last;
                   7798: 	    }
                   7799: 	    if ($realm eq '' && $role eq '') {
                   7800: 		$access=($effect eq 'allow');
                   7801: 	    }
1.402     bowersj2 7802: 	}
1.341     www      7803:     }
                   7804:     return $access;
                   7805: }
                   7806: 
1.103     harris41 7807: # ------------------------------------------------- Check for a user privilege
1.12      www      7808: 
                   7809: sub allowed {
1.1172.2.126  raeburn  7810:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7811:     my $ver_orguri=$uri;
1.439     www      7812:     $uri=&deversion($uri);
1.152     www      7813:     my $orguri=$uri;
1.52      www      7814:     $uri=&declutter($uri);
1.809     raeburn  7815: 
1.810     raeburn  7816:     if ($priv eq 'evb') {
                   7817: # Evade communication block restrictions for specified role in a course
                   7818:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7819:             return $1;
                   7820:         } else {
                   7821:             return;
                   7822:         }
                   7823:     }
                   7824: 
1.620     albertel 7825:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7826: # Free bre access to adm and meta resources
1.1172.2.133  raeburn  7827:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
1.769     albertel 7828: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7829: 	&& ($priv eq 'bre')) {
1.14      www      7830: 	return 'F';
1.159     www      7831:     }
                   7832: 
1.545     banghart 7833: # Free bre access to user's own portfolio contents
1.714     raeburn  7834:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7835:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7836: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7837:         my %setters;
                   7838:         my ($startblock,$endblock) = 
                   7839:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7840:         if ($startblock && $endblock) {
                   7841:             return 'B';
                   7842:         } else {
                   7843:             return 'F';
                   7844:         }
1.545     banghart 7845:     }
                   7846: 
1.762     raeburn  7847: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7848:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7849:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7850:         if (exists($env{'request.course.id'})) {
                   7851:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7852:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7853:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7854:                 my $courseprivid=$env{'request.course.id'};
                   7855:                 $courseprivid=~s/\_/\//;
                   7856:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7857:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7858:                     return $1; 
1.762     raeburn  7859:                 } else {
                   7860:                     if ($env{'request.course.sec'}) {
                   7861:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7862:                     }
                   7863:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7864:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7865:                         return $2;
                   7866:                     }
1.714     raeburn  7867:                 }
                   7868:             }
                   7869:         }
                   7870:     }
                   7871: 
1.159     www      7872: # Free bre to public access
                   7873: 
                   7874:     if ($priv eq 'bre') {
1.238     www      7875:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7876: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7877:            return 'F'; 
                   7878:         }
1.238     www      7879:         if ($copyright eq 'priv') {
                   7880:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7881: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7882: 		return '';
                   7883:             }
                   7884:         }
                   7885:         if ($copyright eq 'domain') {
                   7886:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7887: 	    unless (($env{'user.domain'} eq $1) ||
                   7888:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7889: 		return '';
                   7890:             }
1.262     matthew  7891:         }
1.620     albertel 7892:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7893:             # Library role, so allow browsing of resources in this domain.
                   7894:             return 'F';
1.238     www      7895:         }
1.341     www      7896:         if ($copyright eq 'custom') {
                   7897: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7898:         }
1.14      www      7899:     }
1.264     matthew  7900:     # Domain coordinator is trying to create a course
1.620     albertel 7901:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7902:         # uri is the requested domain in this case.
                   7903:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7904:         # a role of dc for the domain in question.
1.620     albertel 7905:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7906:     }
1.29      www      7907: 
1.52      www      7908:     my $thisallowed='';
                   7909:     my $statecond=0;
                   7910:     my $courseprivid='';
                   7911: 
1.1039    raeburn  7912:     my $ownaccess;
1.1043    raeburn  7913:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7914:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7915:         if ($uri eq '') {
                   7916:             $ownaccess = 1;
                   7917:         } else {
                   7918:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7919:                 my $udom = $env{'user.domain'};
                   7920:                 my $uname = $env{'user.name'};
                   7921:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7922:                     $ownaccess = 1;
1.1040    raeburn  7923:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7924:                     unless ($uri =~ m{\.\./}) {
                   7925:                         $ownaccess = 1;
                   7926:                     }
                   7927:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7928:                     my $now = time;
                   7929:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7930:                         my $adom = $1;
                   7931:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7932:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7933:                                 my ($start,$end) = split('.',$env{$key});
                   7934:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7935:                                     $ownaccess = 1;
                   7936:                                     last;
                   7937:                                 }
                   7938:                             }
                   7939:                         }
                   7940:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7941:                         my $adom = $1;
                   7942:                         my $aname = $2;
1.1042    raeburn  7943:                         foreach my $role ('ca','aa') { 
                   7944:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7945:                                 my ($start,$end) =
                   7946:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7947:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7948:                                     $ownaccess = 1;
                   7949:                                     last;
                   7950:                                 }
1.1039    raeburn  7951:                             }
                   7952:                         }
                   7953:                     }
                   7954:                 }
                   7955:             }
                   7956:         }
                   7957:     }
                   7958: 
1.52      www      7959: # Course
                   7960: 
1.620     albertel 7961:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7962:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7963:             $thisallowed.=$1;
                   7964:         }
1.52      www      7965:     }
1.29      www      7966: 
1.52      www      7967: # Domain
                   7968: 
1.620     albertel 7969:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7970:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7971:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7972:             $thisallowed.=$1;
                   7973:         }
1.12      www      7974:     }
1.52      www      7975: 
1.1141    raeburn  7976: # User who is not author or co-author might still be able to edit
                   7977: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7978:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7979:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7980:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7981:             $thisallowed.=$1;
                   7982:         }
                   7983:     }
                   7984: 
1.52      www      7985: # Course: uri itself is a course
1.66      www      7986:     my $courseuri=$uri;
                   7987:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7988:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7989: 
1.620     albertel 7990:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7991:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  7992:         if ($priv eq 'mip') {
                   7993:             my $rem = $1;
                   7994:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   7995:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   7996:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7997:                 if ($cdom ne '') {
                   7998:                     my %passwdconf = &get_passwdconf($cdom);
                   7999:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8000:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8001:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8002:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8003:                                 unless (@inststatuses) {
                   8004:                                     @inststatuses = ('default');
                   8005:                                 }
                   8006:                                 foreach my $status (@inststatuses) {
                   8007:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8008:                                         $thisallowed.=$rem;
                   8009:                                     }
                   8010:                                 }
                   8011:                             }
                   8012:                         }
                   8013:                     }
                   8014:                 }
                   8015:             }
                   8016:         } else {
                   8017:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8018:                 $thisallowed.=$1;
                   8019:             }
1.1039    raeburn  8020:         }
1.12      www      8021:     }
1.29      www      8022: 
1.665     albertel 8023: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8024: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8025:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8026: 	$thisallowed='';
1.671     raeburn  8027:         my ($match)=&is_on_map($uri);
                   8028:         if ($match) {
                   8029:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8030:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8031:                 my $value = $1;
                   8032:                 if ($noblockcheck) {
                   8033:                     $thisallowed.=$value;
1.1162    raeburn  8034:                 } else {
1.1172.2.126  raeburn  8035:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8036:                     if (@blockers > 0) {
                   8037:                         $thisallowed = 'B';
                   8038:                     } else {
                   8039:                         $thisallowed.=$value;
                   8040:                     }
1.1162    raeburn  8041:                 }
1.671     raeburn  8042:             }
                   8043:         } else {
1.705     albertel 8044:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8045:             if ($refuri) {
                   8046:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8047:                     $thisallowed='F';
1.671     raeburn  8048:                 } else {
                   8049:                     $refuri=&declutter($refuri);
                   8050:                     my ($match) = &is_on_map($refuri);
                   8051:                     if ($match) {
1.1172.2.65  raeburn  8052:                         if ($noblockcheck) {
1.1162    raeburn  8053:                             $thisallowed='F';
1.1172.2.65  raeburn  8054:                         } else {
1.1172.2.127  raeburn  8055:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8056:                             if (@blockers > 0) {
                   8057:                                 $thisallowed = 'B';
                   8058:                             } else {
                   8059:                                 $thisallowed='F';
                   8060:                             }
1.1162    raeburn  8061:                         }
1.671     raeburn  8062:                     }
1.669     raeburn  8063:                 }
1.671     raeburn  8064:             }
                   8065:         }
1.314     www      8066:     }
1.492     albertel 8067: 
1.766     albertel 8068:     if ($priv eq 'bre'
                   8069: 	&& $thisallowed ne 'F' 
                   8070: 	&& $thisallowed ne '2'
                   8071: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8072: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8073:     }
                   8074:     
1.52      www      8075: # Full access at system, domain or course-wide level? Exit.
1.29      www      8076:     if ($thisallowed=~/F/) {
                   8077: 	return 'F';
                   8078:     }
                   8079: 
1.52      www      8080: # If this is generating or modifying users, exit with special codes
1.29      www      8081: 
1.643     www      8082:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8083: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8084: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8085: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8086: 	    unless ($auname) { return $thisallowed; }
                   8087: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8088: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8089: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8090: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8091: 	}
1.52      www      8092: 	return $thisallowed;
                   8093:     }
                   8094: #
1.103     harris41 8095: # Gathered so far: system, domain and course wide privileges
1.52      www      8096: #
                   8097: # Course: See if uri or referer is an individual resource that is part of 
                   8098: # the course
                   8099: 
1.620     albertel 8100:     if ($env{'request.course.id'}) {
1.232     www      8101: 
1.1172.2.115  raeburn  8102: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8103: 
                   8104:         if ($priv eq 'mip') {
                   8105:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8106:                 return $thisallowed;
                   8107:             } else {
                   8108:                 return '';
                   8109:             }
                   8110:         }
                   8111: 
1.620     albertel 8112:        $courseprivid=$env{'request.course.id'};
                   8113:        if ($env{'request.course.sec'}) {
                   8114:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8115:        }
                   8116:        $courseprivid=~s/\_/\//;
                   8117:        my $checkreferer=1;
1.232     www      8118:        my ($match,$cond)=&is_on_map($uri);
                   8119:        if ($match) {
                   8120:            $statecond=$cond;
1.620     albertel 8121:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8122:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8123:                my $value = $1;
                   8124:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8125:                    if ($noblockcheck) {
1.1162    raeburn  8126:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8127:                    } else {
1.1172.2.126  raeburn  8128:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8129:                        if (@blockers > 0) {
                   8130:                            $thisallowed = 'B';
                   8131:                        } else {
                   8132:                            $thisallowed.=$value;
                   8133:                        }
1.1162    raeburn  8134:                    }
                   8135:                } else {
                   8136:                    $thisallowed.=$value;
                   8137:                }
1.52      www      8138:                $checkreferer=0;
                   8139:            }
1.29      www      8140:        }
1.1172.2.126  raeburn  8141: 
1.148     www      8142:        if ($checkreferer) {
1.620     albertel 8143: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8144:             unless ($refuri) {
1.800     albertel 8145:                 foreach my $key (keys(%env)) {
                   8146: 		    if ($key=~/^httpref\..*\*/) {
                   8147: 			my $pattern=$key;
1.156     www      8148:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8149:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8150:                         $pattern=~s/\//\\\//g;
1.152     www      8151:                         if ($orguri=~/$pattern/) {
1.800     albertel 8152: 			    $refuri=$env{$key};
1.148     www      8153:                         }
                   8154:                     }
1.191     harris41 8155:                 }
1.148     www      8156:             }
1.232     www      8157: 
1.148     www      8158:          if ($refuri) { 
1.152     www      8159: 	  $refuri=&declutter($refuri);
1.232     www      8160:           my ($match,$cond)=&is_on_map($refuri);
                   8161:             if ($match) {
                   8162:               my $refstatecond=$cond;
1.620     albertel 8163:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8164:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8165:                   my $value = $1;
                   8166:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8167:                       if ($noblockcheck) {
1.1162    raeburn  8168:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8169:                       } else {
1.1172.2.127  raeburn  8170:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8171:                           if (@blockers > 0) {
                   8172:                               $thisallowed = 'B';
                   8173:                           } else {
                   8174:                               $thisallowed.=$value;
                   8175:                           }
1.1162    raeburn  8176:                       }
                   8177:                   } else {
                   8178:                       $thisallowed.=$value;
                   8179:                   }
1.53      www      8180:                   $uri=$refuri;
                   8181:                   $statecond=$refstatecond;
1.52      www      8182:               }
                   8183:           }
1.148     www      8184:         }
1.29      www      8185:        }
1.52      www      8186:    }
1.29      www      8187: 
1.52      www      8188: #
1.103     harris41 8189: # Gathered now: all privileges that could apply, and condition number
1.52      www      8190: # 
                   8191: #
                   8192: # Full or no access?
                   8193: #
1.29      www      8194: 
1.52      www      8195:     if ($thisallowed=~/F/) {
                   8196: 	return 'F';
                   8197:     }
1.29      www      8198: 
1.52      www      8199:     unless ($thisallowed) {
                   8200:         return '';
                   8201:     }
1.29      www      8202: 
1.52      www      8203: # Restrictions exist, deal with them
                   8204: #
                   8205: #   C:according to course preferences
                   8206: #   R:according to resource settings
                   8207: #   L:unless locked
                   8208: #   X:according to user session state
                   8209: #
                   8210: 
                   8211: # Possibly locked functionality, check all courses
1.54      www      8212: # Locks might take effect only after 10 minutes cache expiration for other
                   8213: # courses, and 2 minutes for current course
1.52      www      8214: 
                   8215:     my $envkey;
                   8216:     if ($thisallowed=~/L/) {
1.1000    raeburn  8217:         foreach $envkey (keys(%env)) {
1.54      www      8218:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8219:                my $courseid=$2;
                   8220:                my $roleid=$1.'.'.$2;
1.92      www      8221:                $courseid=~s/^\///;
1.54      www      8222:                my $expiretime=600;
1.620     albertel 8223:                if ($env{'request.role'} eq $roleid) {
1.54      www      8224: 		  $expiretime=120;
                   8225:                }
                   8226: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8227:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8228:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8229: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8230:                }
1.620     albertel 8231:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8232:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8233: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8234:                        &log($env{'user.domain'},$env{'user.name'},
                   8235:                             $env{'user.home'},
1.57      www      8236:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8237:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8238:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8239: 		       return '';
                   8240:                    }
                   8241:                }
1.620     albertel 8242:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8243:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8244: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8245:                        &log($env{'user.domain'},$env{'user.name'},
                   8246:                             $env{'user.home'},
1.57      www      8247:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8248:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8249:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8250: 		       return '';
                   8251:                    }
                   8252:                }
                   8253: 	   }
1.29      www      8254:        }
1.52      www      8255:     }
1.1172.2.126  raeburn  8256: 
1.52      www      8257: #
                   8258: # Rest of the restrictions depend on selected course
                   8259: #
                   8260: 
1.620     albertel 8261:     unless ($env{'request.course.id'}) {
1.766     albertel 8262: 	if ($thisallowed eq 'A') {
                   8263: 	    return 'A';
1.814     raeburn  8264:         } elsif ($thisallowed eq 'B') {
                   8265:             return 'B';
1.766     albertel 8266: 	} else {
                   8267: 	    return '1';
                   8268: 	}
1.52      www      8269:     }
1.29      www      8270: 
1.52      www      8271: #
                   8272: # Now user is definitely in a course
                   8273: #
1.53      www      8274: 
                   8275: 
                   8276: # Course preferences
                   8277: 
                   8278:    if ($thisallowed=~/C/) {
1.620     albertel 8279:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8280:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8281:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8282: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8283: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8284: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8285: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8286: 			$env{'request.course.id'});
                   8287: 	   }
1.237     www      8288:            return '';
                   8289:        }
                   8290: 
1.620     albertel 8291:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8292: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8293: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8294: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8295: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8296: 			$env{'request.course.id'});
                   8297: 	   }
1.54      www      8298:            return '';
                   8299:        }
1.53      www      8300:    }
                   8301: 
                   8302: # Resource preferences
                   8303: 
                   8304:    if ($thisallowed=~/R/) {
1.620     albertel 8305:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8306:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8307: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8308: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8309: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8310: 	   }
                   8311: 	   return '';
1.54      www      8312:        }
1.53      www      8313:    }
1.30      www      8314: 
1.246     www      8315: # Restricted by state or randomout?
1.30      www      8316: 
1.52      www      8317:    if ($thisallowed=~/X/) {
1.620     albertel 8318:       if ($env{'acc.randomout'}) {
1.579     albertel 8319: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8320:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8321:             return ''; 
                   8322:          }
1.247     www      8323:       }
                   8324:       if (&condval($statecond)) {
1.52      www      8325: 	 return '2';
                   8326:       } else {
                   8327:          return '';
                   8328:       }
                   8329:    }
1.30      www      8330: 
1.766     albertel 8331:     if ($thisallowed eq 'A') {
                   8332: 	return 'A';
1.814     raeburn  8333:     } elsif ($thisallowed eq 'B') {
                   8334:         return 'B';
1.766     albertel 8335:     }
1.52      www      8336:    return 'F';
1.232     www      8337: }
1.1162    raeburn  8338: 
1.1172.2.13  raeburn  8339: # ------------------------------------------- Check construction space access
                   8340: 
                   8341: sub constructaccess {
                   8342:     my ($url,$setpriv)=@_;
                   8343: 
                   8344: # We do not allow editing of previous versions of files
                   8345:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8346: 
                   8347: # Get username and domain from URL
                   8348:     my ($ownername,$ownerdomain,$ownerhome);
                   8349: 
                   8350:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8351:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8352: 
                   8353: # The URL does not really point to any authorspace, forget it
                   8354:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8355: 
                   8356: # Now we need to see if the user has access to the authorspace of
                   8357: # $ownername at $ownerdomain
                   8358: 
                   8359:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8360: # Real author for this?
                   8361:        $ownerhome = $env{'user.home'};
                   8362:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8363:           return ($ownername,$ownerdomain,$ownerhome);
                   8364:        }
                   8365:     } else {
                   8366: # Co-author for this?
                   8367:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8368:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8369:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8370:             return ($ownername,$ownerdomain,$ownerhome);
                   8371:         }
                   8372:     }
                   8373: 
                   8374: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8375: # we might as well leave
                   8376:    unless ($setpriv) { return ''; }
                   8377: 
                   8378: # Backdoor access?
                   8379:     my $allowed=&allowed('eco',$ownerdomain);
                   8380: # Nope
                   8381:     unless ($allowed) { return ''; }
                   8382: # Looks like we may have access, but could be locked by the owner of the construction space
                   8383:     if ($allowed eq 'U') {
                   8384:         my %blocked=&get('environment',['domcoord.author'],
                   8385:                          $ownerdomain,$ownername);
                   8386: # Is blocked by owner
                   8387:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8388:     }
                   8389:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8390: # Grant temporary access
                   8391:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8392:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8393:         if (!$update) { $update = $then; }
                   8394:         my $refresh=$env{'user.refresh.time'};
                   8395:         if (!$refresh) { $refresh = $update; }
                   8396:         my $now = time;
                   8397:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8398:                            $now,'ca','constructaccess');
                   8399:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8400:         return($ownername,$ownerdomain,$ownerhome);
                   8401:     }
                   8402: # No business here
                   8403:     return '';
                   8404: }
                   8405: 
1.1172.2.66  raeburn  8406: # ----------------------------------------------------------- Content Blocking
                   8407: 
                   8408: {
                   8409: # Caches for faster Course Contents display where content blocking
                   8410: # is in operation (i.e., interval param set) for timed quiz.
                   8411: #
                   8412: # User for whom data are being temporarily cached.
                   8413: my $cacheduser='';
1.1172.2.126  raeburn  8414: # Course for which data are being temporarily cached.
                   8415: my $cachedcid='';
1.1172.2.66  raeburn  8416: # Cached blockers for this user (a hash of blocking items).
                   8417: my %cachedblockers=();
                   8418: # When the data were last cached.
                   8419: my $cachedlast='';
                   8420: 
                   8421: sub load_all_blockers {
1.1172.2.128  raeburn  8422:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8423:     if (($uname ne '') && ($udom ne '')) {
                   8424:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8425:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8426:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8427:             return;
                   8428:         }
                   8429:     }
                   8430:     $cachedlast=time;
                   8431:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8432:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8433:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8434:     return;
1.1172.2.66  raeburn  8435: }
                   8436: 
1.1162    raeburn  8437: sub get_comm_blocks {
                   8438:     my ($cdom,$cnum) = @_;
                   8439:     if ($cdom eq '' || $cnum eq '') {
                   8440:         return unless ($env{'request.course.id'});
                   8441:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8442:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8443:     }
                   8444:     my %commblocks;
                   8445:     my $hashid=$cdom.'_'.$cnum;
                   8446:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8447:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8448:         %commblocks = %{$blocksref};
                   8449:     } else {
                   8450:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8451:         my $cachetime = 600;
                   8452:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8453:     }
                   8454:     return %commblocks;
                   8455: }
                   8456: 
1.1172.2.66  raeburn  8457: sub get_commblock_resources {
                   8458:     my ($blocks) = @_;
                   8459:     my %blockers = ();
                   8460:     return %blockers unless ($env{'request.course.id'});
                   8461:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8462:     my %commblocks;
                   8463:     if (ref($blocks) eq 'HASH') {
                   8464:         %commblocks = %{$blocks};
                   8465:     } else {
                   8466:         %commblocks = &get_comm_blocks();
                   8467:     }
1.1172.2.66  raeburn  8468:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8469:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8470:     return %blockers unless (ref($navmap));
                   8471:     my $now = time;
1.1162    raeburn  8472:     foreach my $block (keys(%commblocks)) {
                   8473:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8474:             my ($start,$end) = ($1,$2);
                   8475:             if ($start <= $now && $end >= $now) {
                   8476:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8477:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8478:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8479:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8480:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8481:                             }
                   8482:                         }
                   8483:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8484:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8485:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8486:                             }
                   8487:                         }
                   8488:                     }
                   8489:                 }
                   8490:             }
                   8491:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8492:             my $item = $1;
1.1163    raeburn  8493:             my @to_test;
1.1162    raeburn  8494:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8495:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8496:                     my @interval;
                   8497:                     my $type = 'map';
                   8498:                     if ($item eq 'course') {
                   8499:                         $type = 'course';
                   8500:                         @interval=&EXT("resource.0.interval");
                   8501:                     } else {
                   8502:                         if ($item =~ /___\d+___/) {
                   8503:                             $type = 'resource';
                   8504:                             @interval=&EXT("resource.0.interval",$item);
                   8505:                             if (ref($navmap)) {
                   8506:                                 my $res = $navmap->getBySymb($item);
                   8507:                                 push(@to_test,$res);
                   8508:                             }
1.1162    raeburn  8509:                         } else {
1.1172.2.66  raeburn  8510:                             my $mapsymb = &symbread($item,1);
                   8511:                             if ($mapsymb) {
                   8512:                                 if (ref($navmap)) {
                   8513:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.129  raeburn  8514:                                     if (ref($mapres)) {
                   8515:                                         my $first = $mapres->map_start();
                   8516:                                         my $finish = $mapres->map_finish();
                   8517:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8518:                                         if (ref($it)) {
                   8519:                                             my $res;
                   8520:                                             while ($res = $it->next(undef,1)) {
                   8521:                                                 next unless (ref($res));
                   8522:                                                 my $symb = $res->symb();
                   8523:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8524:                                                 @interval=&EXT("resource.0.interval",$symb);
                   8525:                                                 if ($interval[1] eq 'map') {
                   8526:                                                     if ($res->answerable()) {
                   8527:                                                         push(@to_test,$res);
                   8528:                                                         last;
                   8529:                                                     }
                   8530:                                                 }
1.1162    raeburn  8531:                                             }
                   8532:                                         }
                   8533:                                     }
                   8534:                                 }
                   8535:                             }
                   8536:                         }
1.1172.2.66  raeburn  8537:                     }
                   8538:                     if ($interval[0] =~ /^\d+$/) {
                   8539:                         my $first_access;
                   8540:                         if ($type eq 'resource') {
                   8541:                             $first_access=&get_first_access($interval[1],$item);
                   8542:                         } elsif ($type eq 'map') {
                   8543:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8544:                         } else {
                   8545:                             $first_access=&get_first_access($interval[1]);
                   8546:                         }
                   8547:                         if ($first_access) {
                   8548:                             my $timesup = $first_access+$interval[0];
                   8549:                             if ($timesup > $now) {
                   8550:                                 my $activeblock;
                   8551:                                 foreach my $res (@to_test) {
                   8552:                                     if ($res->answerable()) {
                   8553:                                         $activeblock = 1;
                   8554:                                         last;
                   8555:                                     }
                   8556:                                 }
                   8557:                                 if ($activeblock) {
                   8558:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8559:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8560:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8561:                                          }
                   8562:                                     }
                   8563:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8564:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8565:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8566:                                         }
1.1162    raeburn  8567:                                     }
                   8568:                                 }
                   8569:                             }
                   8570:                         }
                   8571:                     }
                   8572:                 }
                   8573:             }
                   8574:         }
                   8575:     }
1.1172.2.66  raeburn  8576:     return %blockers;
1.1162    raeburn  8577: }
                   8578: 
1.1172.2.66  raeburn  8579: sub has_comm_blocking {
1.1172.2.128  raeburn  8580:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8581:     my @blockers;
                   8582:     return unless ($env{'request.course.id'});
                   8583:     return unless ($priv eq 'bre');
                   8584:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8585:     return if ($env{'request.state'} eq 'construct');
1.1172.2.128  raeburn  8586:     my %blockinfo;
                   8587:     if (ref($blocks) eq 'HASH') {
                   8588:         %blockinfo = &get_commblock_resources($blocks);
                   8589:     } else {
                   8590:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8591:         %blockinfo = %cachedblockers;
                   8592:     }
                   8593:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8594:     my (%possibles,@symbs);
                   8595:     if (!$symb) {
1.1172.2.128  raeburn  8596:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8597:     }
1.1172.2.66  raeburn  8598:     if ($symb) {
                   8599:         @symbs = ($symb);
                   8600:     } elsif (keys(%possibles)) {
                   8601:         @symbs = keys(%possibles);
                   8602:     }
                   8603:     my $noblock;
                   8604:     foreach my $symb (@symbs) {
                   8605:         last if ($noblock);
                   8606:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8607:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8608:             if ($block =~ /^firstaccess____(.+)$/) {
                   8609:                 my $item = $1;
1.1172.2.126  raeburn  8610:                 unless ($blocked) {
                   8611:                     if (($item eq $map) || ($item eq $symb)) {
                   8612:                         $noblock = 1;
                   8613:                         last;
                   8614:                     }
1.1172.2.66  raeburn  8615:                 }
1.1162    raeburn  8616:             }
1.1172.2.128  raeburn  8617:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8618:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8619:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8620:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8621:                             push(@blockers,$block);
                   8622:                         }
                   8623:                     }
                   8624:                 }
1.1172.2.128  raeburn  8625:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8626:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8627:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8628:                             push(@blockers,$block);
                   8629:                         }
1.1172.2.66  raeburn  8630:                     }
                   8631:                 }
1.1162    raeburn  8632:             }
                   8633:         }
                   8634:     }
1.1172.2.126  raeburn  8635:     unless ($noblock) {
                   8636:         return @blockers;
                   8637:     }
                   8638:     return;
1.1172.2.66  raeburn  8639: }
1.1162    raeburn  8640: }
                   8641: 
1.1172.2.66  raeburn  8642: # -------------------------------- Deversion and split uri into path an filename
                   8643: 
1.1133    foxr     8644: #
1.1172.2.66  raeburn  8645: #   Removes the version from a URI and
1.1133    foxr     8646: #   splits it in to its filename and path to the filename.
                   8647: #   Seems like File::Basename could have done this more clearly.
                   8648: #   Parameters:
                   8649: #      $uri   - input URI
                   8650: #   Returns:
                   8651: #     Two element list consisting of 
                   8652: #     $pathname  - the URI up to and excluding the trailing /
                   8653: #     $filename  - The part of the URI following the last /
                   8654: #  NOTE:
                   8655: #    Another realization of this is simply:
                   8656: #    use File::Basename;
                   8657: #    ...
                   8658: #    $uri = shift;
                   8659: #    $filename = basename($uri);
                   8660: #    $path     = dirname($uri);
                   8661: #    return ($filename, $path);
                   8662: #
                   8663: #     The implementation below is probably faster however.
                   8664: #
1.710     albertel 8665: sub split_uri_for_cond {
                   8666:     my $uri=&deversion(&declutter(shift));
                   8667:     my @uriparts=split(/\//,$uri);
                   8668:     my $filename=pop(@uriparts);
                   8669:     my $pathname=join('/',@uriparts);
                   8670:     return ($pathname,$filename);
                   8671: }
1.232     www      8672: # --------------------------------------------------- Is a resource on the map?
                   8673: 
                   8674: sub is_on_map {
1.710     albertel 8675:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8676:     #Trying to find the conditional for the file
1.620     albertel 8677:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8678: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8679:     if ($match) {
1.289     bowersj2 8680: 	return (1,$1);
                   8681:     } else {
1.434     www      8682: 	return (0,0);
1.289     bowersj2 8683:     }
1.12      www      8684: }
                   8685: 
1.427     www      8686: # --------------------------------------------------------- Get symb from alias
                   8687: 
                   8688: sub get_symb_from_alias {
                   8689:     my $symb=shift;
                   8690:     my ($map,$resid,$url)=&decode_symb($symb);
                   8691: # Already is a symb
                   8692:     if ($url) { return $symb; }
                   8693: # Must be an alias
                   8694:     my $aliassymb='';
                   8695:     my %bighash;
1.620     albertel 8696:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8697:                             &GDBM_READER(),0640)) {
                   8698:         my $rid=$bighash{'mapalias_'.$symb};
                   8699: 	if ($rid) {
                   8700: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8701: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8702: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8703: 	}
                   8704:         untie %bighash;
                   8705:     }
                   8706:     return $aliassymb;
                   8707: }
                   8708: 
1.12      www      8709: # ----------------------------------------------------------------- Define Role
                   8710: 
                   8711: sub definerole {
                   8712:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8713:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8714:     foreach my $role (split(':',$sysrole)) {
                   8715: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8716:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8717:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8718: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8719:                return "refused:s:$crole&$cqual"; 
                   8720:             }
                   8721:         }
1.191     harris41 8722:     }
1.800     albertel 8723:     foreach my $role (split(':',$domrole)) {
                   8724: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8725:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8726:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8727: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8728:                return "refused:d:$crole&$cqual"; 
                   8729:             }
                   8730:         }
1.191     harris41 8731:     }
1.800     albertel 8732:     foreach my $role (split(':',$courole)) {
                   8733: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8734:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8735:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8736: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8737:                return "refused:c:$crole&$cqual"; 
                   8738:             }
                   8739:         }
1.191     harris41 8740:     }
1.1172.2.84  raeburn  8741:     my $uhome;
                   8742:     if (($uname ne '') && ($udom ne '')) {
                   8743:         $uhome = &homeserver($uname,$udom);
                   8744:         return $uhome if ($uhome eq 'no_host');
                   8745:     } else {
                   8746:         $uname = $env{'user.name'};
                   8747:         $udom = $env{'user.domain'};
                   8748:         $uhome = $env{'user.home'};
                   8749:     }
1.620     albertel 8750:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8751:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8752:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8753:     return reply($command,$uhome);
1.12      www      8754:   } else {
                   8755:     return 'refused';
                   8756:   }
1.105     harris41 8757: }
                   8758: 
                   8759: # ---------------- Make a metadata query against the network of library servers
                   8760: 
                   8761: sub metadata_query {
1.1172.2.33  raeburn  8762:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8763:     my %rhash;
1.845     albertel 8764:     my %libserv = &all_library();
1.244     matthew  8765:     my @server_list = (defined($server_array) ? @$server_array
                   8766:                                               : keys(%libserv) );
                   8767:     for my $server (@server_list) {
1.1172.2.33  raeburn  8768:         my $domains = '';
                   8769:         if (ref($domains_hash) eq 'HASH') {
                   8770:             $domains = $domains_hash->{$server};    
                   8771:         }
1.118     harris41 8772: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8773: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8774: 	    $rhash{$server}=$reply;
                   8775: 	}
                   8776: 	else {
                   8777: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8778: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8779: 			     $server);
                   8780: 	    $rhash{$server}=$reply;
                   8781: 	}
1.112     harris41 8782:     }
1.118     harris41 8783:     return \%rhash;
1.240     www      8784: }
                   8785: 
                   8786: # ----------------------------------------- Send log queries and wait for reply
                   8787: 
                   8788: sub log_query {
                   8789:     my ($uname,$udom,$query,%filters)=@_;
                   8790:     my $uhome=&homeserver($uname,$udom);
                   8791:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8792:     my $uhost=&hostname($uhome);
1.800     albertel 8793:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8794:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8795:                        $uhome);
1.479     albertel 8796:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8797:     return get_query_reply($queryid);
                   8798: }
                   8799: 
1.818     raeburn  8800: # -------------------------- Update MySQL table for portfolio file
                   8801: 
                   8802: sub update_portfolio_table {
1.821     raeburn  8803:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8804:     if ($group ne '') {
                   8805:         $file_name =~s /^\Q$group\E//;
                   8806:     }
1.818     raeburn  8807:     my $homeserver = &homeserver($uname,$udom);
                   8808:     my $queryid=
1.821     raeburn  8809:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8810:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8811:     my $reply = &get_query_reply($queryid);
                   8812:     return $reply;
                   8813: }
                   8814: 
1.899     raeburn  8815: # -------------------------- Update MySQL allusers table
                   8816: 
                   8817: sub update_allusers_table {
                   8818:     my ($uname,$udom,$names) = @_;
                   8819:     my $homeserver = &homeserver($uname,$udom);
                   8820:     my $queryid=
                   8821:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8822:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8823:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8824:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8825:                'generation='.&escape($names->{'generation'}).'%%'.
                   8826:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8827:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8828:     return;
1.899     raeburn  8829: }
                   8830: 
1.508     raeburn  8831: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8832: 
                   8833: sub fetch_enrollment_query {
1.511     raeburn  8834:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8835:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8836:     my $maxtries = 1;
1.508     raeburn  8837:     if ($context eq 'automated') {
                   8838:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8839:         $sleep = 2;
                   8840:         $loopmax = 100;
1.547     raeburn  8841:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8842:     } else {
                   8843:         $homeserver = &homeserver($cnum,$dom);
                   8844:     }
1.838     albertel 8845:     my $host=&hostname($homeserver);
1.506     raeburn  8846:     my $cmd = '';
1.1000    raeburn  8847:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8848:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8849:     }
                   8850:     $cmd =~ s/%%$//;
                   8851:     $cmd = &escape($cmd);
                   8852:     my $query = 'fetchenrollment';
1.620     albertel 8853:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8854:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8855:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8856:         return 'error: '.$queryid;
                   8857:     }
1.1172.2.93  raeburn  8858:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8859:     my $tries = 1;
                   8860:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8861:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8862:         $tries ++;
                   8863:     }
1.526     raeburn  8864:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8865:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8866:     } else {
1.901     albertel 8867:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8868:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8869:             foreach my $line (@responses) {
                   8870:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8871:                 $$replyref{$key} = $value;
                   8872:             }
                   8873:         } else {
1.1117    foxr     8874:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8875:             foreach my $line (@responses) {
                   8876:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8877:                 $$replyref{$key} = $value;
                   8878:                 if ($value > 0) {
1.800     albertel 8879:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8880:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8881:                         my $destname = $pathname.'/'.$filename;
                   8882:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8883:                         if ($xml_classlist =~ /^error/) {
                   8884:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8885:                         } else {
1.1172.2.96  raeburn  8886:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8887:                                 print FILE &unescape($xml_classlist);
                   8888:                                 close(FILE);
1.526     raeburn  8889:                             } else {
                   8890:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8891:                             }
                   8892:                         }
                   8893:                     }
                   8894:                 }
                   8895:             }
                   8896:         }
                   8897:         return 'ok';
                   8898:     }
                   8899:     return 'error';
                   8900: }
                   8901: 
1.242     www      8902: sub get_query_reply {
1.1172.2.79  raeburn  8903:     my ($queryid,$sleep,$loopmax) = @_;
                   8904:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8905:         $sleep = 0.2;
                   8906:     }
                   8907:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8908:         $loopmax = 100;
                   8909:     }
1.1117    foxr     8910:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8911:     my $reply='';
1.1172.2.79  raeburn  8912:     for (1..$loopmax) {
                   8913: 	sleep($sleep);
1.240     www      8914:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8915: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8916: 		$reply = join('',<$fh>);
                   8917: 		close($fh);
1.240     www      8918: 	   } else { return 'error: reply_file_error'; }
1.242     www      8919:            return &unescape($reply);
                   8920: 	}
1.240     www      8921:     }
1.242     www      8922:     return 'timeout:'.$queryid;
1.240     www      8923: }
                   8924: 
                   8925: sub courselog_query {
1.241     www      8926: #
                   8927: # possible filters:
                   8928: # url: url or symb
                   8929: # username
                   8930: # domain
                   8931: # action: view, submit, grade
                   8932: # start: timestamp
                   8933: # end: timestamp
                   8934: #
1.240     www      8935:     my (%filters)=@_;
1.620     albertel 8936:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8937:     if ($filters{'url'}) {
                   8938: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8939:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8940:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8941:     }
1.620     albertel 8942:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8943:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8944:     return &log_query($cname,$cdom,'courselog',%filters);
                   8945: }
                   8946: 
                   8947: sub userlog_query {
1.858     raeburn  8948: #
                   8949: # possible filters:
                   8950: # action: log check role
                   8951: # start: timestamp
                   8952: # end: timestamp
                   8953: #
1.240     www      8954:     my ($uname,$udom,%filters)=@_;
                   8955:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8956: }
                   8957: 
1.506     raeburn  8958: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8959: 
                   8960: sub auto_run {
1.508     raeburn  8961:     my ($cnum,$cdom) = @_;
1.876     raeburn  8962:     my $response = 0;
                   8963:     my $settings;
                   8964:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8965:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8966:         $settings = $domconfig{'autoenroll'};
                   8967:         if ($settings->{'run'} eq '1') {
                   8968:             $response = 1;
                   8969:         }
                   8970:     } else {
1.934     raeburn  8971:         my $homeserver;
                   8972:         if (&is_course($cdom,$cnum)) {
                   8973:             $homeserver = &homeserver($cnum,$cdom);
                   8974:         } else {
                   8975:             $homeserver = &domain($cdom,'primary');
                   8976:         }
                   8977:         if ($homeserver ne 'no_host') {
                   8978:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8979:         }
1.876     raeburn  8980:     }
1.506     raeburn  8981:     return $response;
                   8982: }
1.776     albertel 8983: 
1.506     raeburn  8984: sub auto_get_sections {
1.508     raeburn  8985:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8986:     my $homeserver;
                   8987:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8988:         $homeserver = &homeserver($cnum,$cdom);
                   8989:     }
                   8990:     if (!defined($homeserver)) { 
                   8991:         if ($cdom =~ /^$match_domain$/) {
                   8992:             $homeserver = &domain($cdom,'primary');
                   8993:         }
                   8994:     }
                   8995:     my @secs;
                   8996:     if (defined($homeserver)) {
                   8997:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8998:         unless ($response eq 'refused') {
                   8999:             @secs = split(/:/,$response);
                   9000:         }
1.506     raeburn  9001:     }
                   9002:     return @secs;
                   9003: }
1.776     albertel 9004: 
1.506     raeburn  9005: sub auto_new_course {
1.1099    raeburn  9006:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9007:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9008:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9009:     return $response;
                   9010: }
1.776     albertel 9011: 
1.506     raeburn  9012: sub auto_validate_courseID {
1.508     raeburn  9013:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9014:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9015:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9016:     return $response;
                   9017: }
1.776     albertel 9018: 
1.1007    raeburn  9019: sub auto_validate_instcode {
1.1020    raeburn  9020:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9021:     my ($homeserver,$response);
                   9022:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9023:         $homeserver = &homeserver($cnum,$cdom);
                   9024:     }
                   9025:     if (!defined($homeserver)) {
                   9026:         if ($cdom =~ /^$match_domain$/) {
                   9027:             $homeserver = &domain($cdom,'primary');
                   9028:         }
                   9029:     }
1.1065    raeburn  9030:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9031:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9032:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9033:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9034: }
                   9035: 
1.506     raeburn  9036: sub auto_create_password {
1.873     raeburn  9037:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9038:     my ($homeserver,$response);
1.506     raeburn  9039:     my $create_passwd = 0;
                   9040:     my $authchk = '';
1.873     raeburn  9041:     if ($udom =~ /^$match_domain$/) {
                   9042:         $homeserver = &domain($udom,'primary');
                   9043:     }
                   9044:     if ($homeserver eq '') {
                   9045:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9046:             $homeserver = &homeserver($cnum,$cdom);
                   9047:         }
                   9048:     }
                   9049:     if ($homeserver eq '') {
                   9050:         $authchk = 'nodomain';
1.506     raeburn  9051:     } else {
1.873     raeburn  9052:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9053:         if ($response eq 'refused') {
                   9054:             $authchk = 'refused';
                   9055:         } else {
1.901     albertel 9056:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9057:         }
1.506     raeburn  9058:     }
                   9059:     return ($authparam,$create_passwd,$authchk);
                   9060: }
                   9061: 
1.706     raeburn  9062: sub auto_photo_permission {
                   9063:     my ($cnum,$cdom,$students) = @_;
                   9064:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9065:     my ($outcome,$perm_reqd,$conditions) = 
                   9066: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9067:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9068: 	return (undef,undef);
                   9069:     }
1.706     raeburn  9070:     return ($outcome,$perm_reqd,$conditions);
                   9071: }
                   9072: 
                   9073: sub auto_checkphotos {
                   9074:     my ($uname,$udom,$pid) = @_;
                   9075:     my $homeserver = &homeserver($uname,$udom);
                   9076:     my ($result,$resulttype);
                   9077:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9078: 				   &escape($uname).':'.&escape($pid),
                   9079: 				   $homeserver));
1.709     albertel 9080:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9081: 	return (undef,undef);
                   9082:     }
1.706     raeburn  9083:     if ($outcome) {
                   9084:         ($result,$resulttype) = split(/:/,$outcome);
                   9085:     } 
                   9086:     return ($result,$resulttype);
                   9087: }
                   9088: 
                   9089: sub auto_photochoice {
                   9090:     my ($cnum,$cdom) = @_;
                   9091:     my $homeserver = &homeserver($cnum,$cdom);
                   9092:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9093: 						       &escape($cdom),
                   9094: 						       $homeserver)));
1.709     albertel 9095:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9096: 	return (undef,undef);
                   9097:     }
1.706     raeburn  9098:     return ($update,$comment);
                   9099: }
                   9100: 
                   9101: sub auto_photoupdate {
                   9102:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9103:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9104:     my $host=&hostname($homeserver);
1.706     raeburn  9105:     my $cmd = '';
                   9106:     my $maxtries = 1;
1.800     albertel 9107:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9108:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9109:     }
                   9110:     $cmd =~ s/%%$//;
                   9111:     $cmd = &escape($cmd);
                   9112:     my $query = 'institutionalphotos';
                   9113:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9114:     unless ($queryid=~/^\Q$host\E\_/) {
                   9115:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9116:         return 'error: '.$queryid;
                   9117:     }
                   9118:     my $reply = &get_query_reply($queryid);
                   9119:     my $tries = 1;
                   9120:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9121:         $reply = &get_query_reply($queryid);
                   9122:         $tries ++;
                   9123:     }
                   9124:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9125:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9126:     } else {
                   9127:         my @responses = split(/:/,$reply);
                   9128:         my $outcome = shift(@responses); 
                   9129:         foreach my $item (@responses) {
                   9130:             my ($key,$value) = split(/=/,$item);
                   9131:             $$photo{$key} = $value;
                   9132:         }
                   9133:         return $outcome;
                   9134:     }
                   9135:     return 'error';
                   9136: }
                   9137: 
1.521     raeburn  9138: sub auto_instcode_format {
1.793     albertel 9139:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9140: 	$cat_order) = @_;
1.521     raeburn  9141:     my $courses = '';
1.772     raeburn  9142:     my @homeservers;
1.521     raeburn  9143:     if ($caller eq 'global') {
1.841     albertel 9144: 	my %servers = &get_servers($codedom,'library');
                   9145: 	foreach my $tryserver (keys(%servers)) {
                   9146: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9147: 		push(@homeservers,$tryserver);
                   9148: 	    }
1.584     raeburn  9149:         }
1.1022    raeburn  9150:     } elsif ($caller eq 'requests') {
                   9151:         if ($codedom =~ /^$match_domain$/) {
                   9152:             my $chome = &domain($codedom,'primary');
                   9153:             unless ($chome eq 'no_host') {
                   9154:                 push(@homeservers,$chome);
                   9155:             }
                   9156:         }
1.521     raeburn  9157:     } else {
1.772     raeburn  9158:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9159:     }
1.793     albertel 9160:     foreach my $code (keys(%{$instcodes})) {
                   9161:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9162:     }
                   9163:     chop($courses);
1.772     raeburn  9164:     my $ok_response = 0;
                   9165:     my $response;
                   9166:     while (@homeservers > 0 && $ok_response == 0) {
                   9167:         my $server = shift(@homeservers); 
                   9168:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9169:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9170:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9171: 		split(/:/,$response);
1.772     raeburn  9172:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9173:             push(@{$codetitles},&str2array($codetitles_str));
                   9174:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9175:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9176:             $ok_response = 1;
                   9177:         }
                   9178:     }
                   9179:     if ($ok_response) {
1.521     raeburn  9180:         return 'ok';
1.772     raeburn  9181:     } else {
                   9182:         return $response;
1.521     raeburn  9183:     }
                   9184: }
                   9185: 
1.792     raeburn  9186: sub auto_instcode_defaults {
                   9187:     my ($domain,$returnhash,$code_order) = @_;
                   9188:     my @homeservers;
1.841     albertel 9189: 
                   9190:     my %servers = &get_servers($domain,'library');
                   9191:     foreach my $tryserver (keys(%servers)) {
                   9192: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9193: 	    push(@homeservers,$tryserver);
                   9194: 	}
1.792     raeburn  9195:     }
1.841     albertel 9196: 
1.792     raeburn  9197:     my $response;
1.841     albertel 9198:     foreach my $server (@homeservers) {
1.792     raeburn  9199:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9200:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9201: 	
                   9202: 	foreach my $pair (split(/\&/,$response)) {
                   9203: 	    my ($name,$value)=split(/\=/,$pair);
                   9204: 	    if ($name eq 'code_order') {
                   9205: 		@{$code_order} = split(/\&/,&unescape($value));
                   9206: 	    } else {
                   9207: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9208: 	    }
                   9209: 	}
                   9210: 	return 'ok';
1.792     raeburn  9211:     }
1.841     albertel 9212: 
                   9213:     return $response;
1.1003    raeburn  9214: }
                   9215: 
                   9216: sub auto_possible_instcodes {
1.1007    raeburn  9217:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9218:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9219:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9220:         return;
                   9221:     }
1.1003    raeburn  9222:     my (@homeservers,$uhome);
                   9223:     if (defined(&domain($domain,'primary'))) {
                   9224:         $uhome=&domain($domain,'primary');
                   9225:         push(@homeservers,&domain($domain,'primary'));
                   9226:     } else {
                   9227:         my %servers = &get_servers($domain,'library');
                   9228:         foreach my $tryserver (keys(%servers)) {
                   9229:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9230:                 push(@homeservers,$tryserver);
                   9231:             }
                   9232:         }
                   9233:     }
                   9234:     my $response;
                   9235:     foreach my $server (@homeservers) {
                   9236:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9237:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9238:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9239:             split(':',$response);
                   9240:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9241:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9242:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9243:             my ($name,$value)=split('=',$item);
                   9244:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9245:         }
                   9246:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9247:             my ($name,$value)=split('=',$item);
                   9248:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9249:         }
                   9250:         return 'ok';
                   9251:     }
                   9252:     return $response;
                   9253: }
1.792     raeburn  9254: 
1.1010    raeburn  9255: sub auto_courserequest_checks {
                   9256:     my ($dom) = @_;
1.1020    raeburn  9257:     my ($homeserver,%validations);
                   9258:     if ($dom =~ /^$match_domain$/) {
                   9259:         $homeserver = &domain($dom,'primary');
                   9260:     }
                   9261:     unless ($homeserver eq 'no_host') {
                   9262:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9263:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9264:             my @items = split(/&/,$response);
                   9265:             foreach my $item (@items) {
                   9266:                 my ($key,$value) = split('=',$item);
                   9267:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9268:             }
                   9269:         }
                   9270:     }
1.1010    raeburn  9271:     return %validations; 
                   9272: }
                   9273: 
1.1020    raeburn  9274: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9275:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9276:     my ($homeserver,$response);
                   9277:     if ($dom =~ /^$match_domain$/) {
                   9278:         $homeserver = &domain($dom,'primary');
                   9279:     }
1.1172.2.43  raeburn  9280:     unless ($homeserver eq 'no_host') {
                   9281:         my $customdata;
                   9282:         if (ref($custominfo) eq 'HASH') {
                   9283:             $customdata = &freeze_escape($custominfo);
                   9284:         }
1.1020    raeburn  9285:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9286:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9287:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9288:                                     $customdata,$homeserver));
1.1020    raeburn  9289:     }
                   9290:     return $response;
                   9291: }
                   9292: 
1.777     albertel 9293: sub auto_validate_class_sec {
1.918     raeburn  9294:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9295:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9296:     my $ownerlist;
                   9297:     if (ref($owners) eq 'ARRAY') {
                   9298:         $ownerlist = join(',',@{$owners});
                   9299:     } else {
                   9300:         $ownerlist = $owners;
                   9301:     }
1.773     raeburn  9302:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9303:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9304:     return $response;
                   9305: }
                   9306: 
1.1172.2.94  raeburn  9307: sub auto_validate_instclasses {
                   9308:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9309:     my ($homeserver,%validations);
                   9310:     $homeserver = &homeserver($cnum,$cdom);
                   9311:     unless ($homeserver eq 'no_host') {
                   9312:         my $ownerlist;
                   9313:         if (ref($owners) eq 'ARRAY') {
                   9314:             $ownerlist = join(',',@{$owners});
                   9315:         } else {
                   9316:             $ownerlist = $owners;
                   9317:         }
                   9318:         if (ref($classesref) eq 'HASH') {
                   9319:             my $classes = &freeze_escape($classesref);
                   9320:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9321:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9322:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9323:                 my @items = split(/&/,$response);
                   9324:                 foreach my $item (@items) {
                   9325:                     my ($key,$value) = split('=',$item);
                   9326:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9327:                 }
                   9328:             }
                   9329:         }
                   9330:     }
                   9331:     return %validations;
                   9332: }
                   9333: 
1.1172.2.38  raeburn  9334: sub auto_crsreq_update {
                   9335:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9336:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9337:     my ($homeserver,%crsreqresponse);
                   9338:     if ($cdom =~ /^$match_domain$/) {
                   9339:         $homeserver = &domain($cdom,'primary');
                   9340:     }
                   9341:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9342:         my $info;
                   9343:         if (ref($inbound) eq 'HASH') {
                   9344:             $info = &freeze_escape($inbound);
                   9345:         }
                   9346:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9347:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9348:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9349:                             &escape($title).':'.&escape($code).':'.
                   9350:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9351:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9352:             my @items = split(/&/,$response);
                   9353:             foreach my $item (@items) {
                   9354:                 my ($key,$value) = split('=',$item);
                   9355:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9356:             }
                   9357:         }
                   9358:     }
                   9359:     return \%crsreqresponse;
                   9360: }
                   9361: 
1.1172.2.78  raeburn  9362: sub auto_export_grades {
                   9363:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9364:     my ($homeserver,%exportresponse);
                   9365:     if ($cdom =~ /^$match_domain$/) {
                   9366:         $homeserver = &domain($cdom,'primary');
                   9367:     }
                   9368:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9369:         my $info;
                   9370:         if (ref($inforef) eq 'HASH') {
                   9371:             $info = &freeze_escape($inforef);
                   9372:         }
                   9373:         if (ref($gradesref) eq 'HASH') {
                   9374:             my $grades = &freeze_escape($gradesref);
                   9375:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9376:                                 $info.':'.$grades,$homeserver);
                   9377:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9378:                 my @items = split(/&/,$response);
                   9379:                 foreach my $item (@items) {
                   9380:                     my ($key,$value) = split('=',$item);
                   9381:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9382:                 }
                   9383:             }
                   9384:         }
                   9385:     }
                   9386:     return \%exportresponse;
                   9387: }
                   9388: 
1.1172.2.68  raeburn  9389: sub check_instcode_cloning {
                   9390:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9391:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9392:         return;
                   9393:     }
                   9394:     my $canclone;
                   9395:     if (@{$code_order} > 0) {
                   9396:         my $instcoderegexp ='^';
                   9397:         my @clonecodes = split(/\&/,$cloner);
                   9398:         foreach my $item (@{$code_order}) {
                   9399:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9400:                 foreach my $pair (@clonecodes) {
                   9401:                     my ($key,$val) = split(/\=/,$pair,2);
                   9402:                     $val = &unescape($val);
                   9403:                     if ($key eq $item) {
                   9404:                         $instcoderegexp .= '('.$val.')';
                   9405:                         last;
                   9406:                     }
                   9407:                 }
                   9408:             } else {
                   9409:                 $instcoderegexp .= $codedefaults->{$item};
                   9410:             }
                   9411:         }
                   9412:         $instcoderegexp .= '$';
                   9413:         my (@from,@to);
                   9414:         eval {
                   9415:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9416:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9417:         };
                   9418:         if ((@from > 0) && (@to > 0)) {
                   9419:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9420:             if (!@diffs) {
                   9421:                 $canclone = 1;
                   9422:             }
                   9423:         }
                   9424:     }
                   9425:     return $canclone;
                   9426: }
                   9427: 
                   9428: sub default_instcode_cloning {
                   9429:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9430:     my (%codedefaults,@code_order,$canclone);
                   9431:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9432:         %codedefaults = %{$codedefaultsref};
                   9433:         @code_order = @{$codeorderref};
                   9434:     } elsif ($clonedom) {
                   9435:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9436:     }
                   9437:     if (($domdefclone) && (@code_order)) {
                   9438:         my @clonecodes = split(/\+/,$domdefclone);
                   9439:         my $instcoderegexp ='^';
                   9440:         foreach my $item (@code_order) {
                   9441:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9442:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9443:             } else {
                   9444:                 $instcoderegexp .= $codedefaults{$item};
                   9445:             }
                   9446:         }
                   9447:         $instcoderegexp .= '$';
                   9448:         my (@from,@to);
                   9449:         eval {
                   9450:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9451:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9452:         };
                   9453:         if ((@from > 0) && (@to > 0)) {
                   9454:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9455:             if (!@diffs) {
                   9456:                 $canclone = 1;
                   9457:             }
                   9458:         }
                   9459:     }
                   9460:     return $canclone;
                   9461: }
                   9462: 
1.679     raeburn  9463: # ------------------------------------------------------- Course Group routines
                   9464: 
                   9465: sub get_coursegroups {
1.809     raeburn  9466:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9467:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9468: }
                   9469: 
1.679     raeburn  9470: sub modify_coursegroup {
                   9471:     my ($cdom,$cnum,$groupsettings) = @_;
                   9472:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9473: }
                   9474: 
1.809     raeburn  9475: sub toggle_coursegroup_status {
                   9476:     my ($cdom,$cnum,$group,$action) = @_;
                   9477:     my ($from_namespace,$to_namespace);
                   9478:     if ($action eq 'delete') {
                   9479:         $from_namespace = 'coursegroups';
                   9480:         $to_namespace = 'deleted_groups';
                   9481:     } else {
                   9482:         $from_namespace = 'deleted_groups';
                   9483:         $to_namespace = 'coursegroups';
                   9484:     }
                   9485:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9486:     if (my $tmp = &error(%curr_group)) {
                   9487:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9488:         return ('read error',$tmp);
                   9489:     } else {
                   9490:         my %savedsettings = %curr_group; 
1.809     raeburn  9491:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9492:         my $deloutcome;
                   9493:         if ($result eq 'ok') {
1.809     raeburn  9494:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9495:         } else {
                   9496:             return ('write error',$result);
                   9497:         }
                   9498:         if ($deloutcome eq 'ok') {
                   9499:             return 'ok';
                   9500:         } else {
                   9501:             return ('delete error',$deloutcome);
                   9502:         }
                   9503:     }
                   9504: }
                   9505: 
1.679     raeburn  9506: sub modify_group_roles {
1.957     raeburn  9507:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9508:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9509:     my $role = 'gr/'.&escape($userprivs);
                   9510:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9511:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9512:     if ($result eq 'ok') {
                   9513:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9514:     }
1.679     raeburn  9515:     return $result;
                   9516: }
                   9517: 
                   9518: sub modify_coursegroup_membership {
                   9519:     my ($cdom,$cnum,$membership) = @_;
                   9520:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9521:     return $result;
                   9522: }
                   9523: 
1.682     raeburn  9524: sub get_active_groups {
                   9525:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9526:     my $now = time;
                   9527:     my %groups = ();
                   9528:     foreach my $key (keys(%env)) {
1.811     albertel 9529:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9530:             my ($start,$end) = split(/\./,$env{$key});
                   9531:             if (($end!=0) && ($end<$now)) { next; }
                   9532:             if (($start!=0) && ($start>$now)) { next; }
                   9533:             if ($1 eq $cdom && $2 eq $cnum) {
                   9534:                 $groups{$3} = $env{$key} ;
                   9535:             }
                   9536:         }
                   9537:     }
                   9538:     return %groups;
                   9539: }
                   9540: 
1.683     raeburn  9541: sub get_group_membership {
                   9542:     my ($cdom,$cnum,$group) = @_;
                   9543:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9544: }
                   9545: 
                   9546: sub get_users_groups {
                   9547:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9548:     my @usersgroups;
1.683     raeburn  9549:     my $cachetime=1800;
                   9550: 
                   9551:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9552:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9553:     if (defined($cached)) {
1.734     albertel 9554:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9555:     } else {  
                   9556:         $grouplist = '';
1.816     raeburn  9557:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9558:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9559:         my $access_end = $env{'course.'.$courseid.
                   9560:                               '.default_enrollment_end_date'};
                   9561:         my $now = time;
                   9562:         foreach my $key (keys(%roleshash)) {
                   9563:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9564:                 my $group = $1;
                   9565:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9566:                     my $start = $2;
                   9567:                     my $end = $1;
                   9568:                     if ($start == -1) { next; } # deleted from group
                   9569:                     if (($start!=0) && ($start>$now)) { next; }
                   9570:                     if (($end!=0) && ($end<$now)) {
                   9571:                         if ($access_end && $access_end < $now) {
                   9572:                             if ($access_end - $end < 86400) {
                   9573:                                 push(@usersgroups,$group);
1.733     raeburn  9574:                             }
                   9575:                         }
1.817     raeburn  9576:                         next;
1.733     raeburn  9577:                     }
1.817     raeburn  9578:                     push(@usersgroups,$group);
1.683     raeburn  9579:                 }
                   9580:             }
                   9581:         }
1.817     raeburn  9582:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9583:         $grouplist = join(':',@usersgroups);
                   9584:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9585:     }
1.733     raeburn  9586:     return @usersgroups;
1.683     raeburn  9587: }
                   9588: 
                   9589: sub devalidate_getgroups_cache {
                   9590:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9591:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9592: 
1.683     raeburn  9593:     my $hashid="$udom:$uname:$courseid";
                   9594:     &devalidate_cache_new('getgroups',$hashid);
                   9595: }
                   9596: 
1.12      www      9597: # ------------------------------------------------------------------ Plain Text
                   9598: 
                   9599: sub plaintext {
1.988     raeburn  9600:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9601:     if ($short =~ m{^cr/}) {
1.758     albertel 9602: 	return (split('/',$short))[-1];
                   9603:     }
1.742     raeburn  9604:     if (!defined($cid)) {
                   9605:         $cid = $env{'request.course.id'};
                   9606:     }
                   9607:     my %rolenames = (
1.1008    raeburn  9608:                       Course    => 'std',
                   9609:                       Community => 'alt1',
1.742     raeburn  9610:                     );
1.1037    raeburn  9611:     if ($cid ne '') {
                   9612:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9613:             unless ($forcedefault) {
                   9614:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9615:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9616:                 return &Apache::lonlocal::mt($roletext);
                   9617:             }
                   9618:         }
                   9619:     }
                   9620:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9621:         (defined($rolenames{$type})) && 
                   9622:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9623:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9624:     } elsif ($cid ne '') {
                   9625:         my $crstype = $env{'course.'.$cid.'.type'};
                   9626:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9627:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9628:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9629:         }
1.742     raeburn  9630:     }
1.1037    raeburn  9631:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9632: }
                   9633: 
                   9634: # ----------------------------------------------------------------- Assign Role
                   9635: 
                   9636: sub assignrole {
1.957     raeburn  9637:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9638:         $context)=@_;
1.21      www      9639:     my $mrole;
                   9640:     if ($role =~ /^cr\//) {
1.393     www      9641:         my $cwosec=$url;
1.811     albertel 9642:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9643: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9644:            my $refused = 1;
                   9645:            if ($context eq 'requestcourses') {
                   9646:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9647:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9648:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9649:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9650:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9651:                            if ($crsenv{'internal.courseowner'} eq
                   9652:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9653:                                $refused = '';
                   9654:                            }
                   9655:                        }
                   9656:                    }
                   9657:                }
                   9658:            }
                   9659:            if ($refused) {
                   9660:                &logthis('Refused custom assignrole: '.
                   9661:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9662:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9663:                return 'refused';
                   9664:            }
1.104     www      9665:         }
1.21      www      9666:         $mrole='cr';
1.678     raeburn  9667:     } elsif ($role =~ /^gr\//) {
                   9668:         my $cwogrp=$url;
1.811     albertel 9669:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9670:         unless (&allowed('mdg',$cwogrp)) {
                   9671:             &logthis('Refused group assignrole: '.
                   9672:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9673:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9674:             return 'refused';
                   9675:         }
                   9676:         $mrole='gr';
1.21      www      9677:     } else {
1.82      www      9678:         my $cwosec=$url;
1.811     albertel 9679:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9680:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9681:             my $refused;
                   9682:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9683:                 if (!(&allowed('c'.$role,$url))) {
                   9684:                     $refused = 1;
                   9685:                 }
                   9686:             } else {
                   9687:                 $refused = 1;
                   9688:             }
1.947     raeburn  9689:             if ($refused) {
1.1045    raeburn  9690:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9691:                 if (!$selfenroll && $context eq 'course') {
                   9692:                     my %crsenv;
                   9693:                     if ($role eq 'cc' || $role eq 'co') {
                   9694:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9695:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9696:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9697:                                 if ($crsenv{'internal.courseowner'} eq 
                   9698:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9699:                                     $refused = '';
                   9700:                                 }
                   9701:                             }
                   9702:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9703:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9704:                                 if ($crsenv{'internal.courseowner'} eq 
                   9705:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9706:                                     $refused = '';
                   9707:                                 }
                   9708:                             }
                   9709:                         }
                   9710:                     }
                   9711:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9712:                     $refused = '';
1.1017    raeburn  9713:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9714:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9715:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9716:                         my $wrongcc;
                   9717:                         if ($cnum =~ /^$match_community$/) {
                   9718:                             $wrongcc = 1 if ($role eq 'cc');
                   9719:                         } else {
                   9720:                             $wrongcc = 1 if ($role eq 'co');
                   9721:                         }
                   9722:                         unless ($wrongcc) {
                   9723:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9724:                             if ($crsenv{'internal.courseowner'} eq 
                   9725:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9726:                                 $refused = '';
                   9727:                             }
1.1017    raeburn  9728:                         }
                   9729:                     }
1.1172.2.9  raeburn  9730:                 } elsif ($context eq 'requestauthor') {
                   9731:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9732:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9733:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9734:                             $refused = '';
                   9735:                         } else {
                   9736:                             my %domdefaults = &get_domain_defaults($udom);
                   9737:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9738:                                 my $checkbystatus;
                   9739:                                 if ($env{'user.adv'}) {
                   9740:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9741:                                     if ($disposition eq 'automatic') {
                   9742:                                         $refused = '';
                   9743:                                     } elsif ($disposition eq '') {
                   9744:                                         $checkbystatus = 1;
                   9745:                                     }
                   9746:                                 } else {
                   9747:                                     $checkbystatus = 1;
                   9748:                                 }
                   9749:                                 if ($checkbystatus) {
                   9750:                                     if ($env{'environment.inststatus'}) {
                   9751:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9752:                                         foreach my $type (@inststatuses) {
                   9753:                                             if (($type ne '') &&
                   9754:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9755:                                                 $refused = '';
                   9756:                                             }
                   9757:                                         }
                   9758:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9759:                                         $refused = '';
                   9760:                                     }
                   9761:                                 }
                   9762:                             }
                   9763:                         }
                   9764:                     }
1.1017    raeburn  9765:                 }
                   9766:                 if ($refused) {
1.947     raeburn  9767:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9768:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9769: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9770:                     return 'refused';
                   9771:                 }
1.932     raeburn  9772:             }
1.1131    raeburn  9773:         } elsif ($role eq 'au') {
                   9774:             if ($url ne '/'.$udom.'/') {
                   9775:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9776:                          ' to assign author role for '.$uname.':'.$udom.
                   9777:                          ' in domain: '.$url.' refused (wrong domain).');
                   9778:                 return 'refused';
                   9779:             }
1.104     www      9780:         }
1.21      www      9781:         $mrole=$role;
                   9782:     }
1.620     albertel 9783:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9784:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9785:     if ($end) { $command.='_'.$end; }
1.21      www      9786:     if ($start) {
                   9787: 	if ($end) { 
1.81      www      9788:            $command.='_'.$start; 
1.21      www      9789:         } else {
1.81      www      9790:            $command.='_0_'.$start;
1.21      www      9791:         }
                   9792:     }
1.739     raeburn  9793:     my $origstart = $start;
                   9794:     my $origend = $end;
1.957     raeburn  9795:     my $delflag;
1.357     www      9796: # actually delete
                   9797:     if ($deleteflag) {
1.373     www      9798: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9799: # modify command to delete the role
1.620     albertel 9800:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9801:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9802: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9803: # set start and finish to negative values for userrolelog
                   9804:            $start=-1;
                   9805:            $end=-1;
1.957     raeburn  9806:            $delflag = 1;
1.357     www      9807:         }
                   9808:     }
                   9809: # send command
1.349     www      9810:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9811: # log new user role if status is ok
1.349     www      9812:     if ($answer eq 'ok') {
1.663     raeburn  9813: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9814:         if (($role eq 'cc') || ($role eq 'in') ||
                   9815:             ($role eq 'ep') || ($role eq 'ad') ||
                   9816:             ($role eq 'ta') || ($role eq 'st') ||
                   9817:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9818:             ($role eq 'co')) {
1.1172.2.13  raeburn  9819: # for course roles, perform group memberships changes triggered by role change.
                   9820:             unless ($role =~ /^gr/) {
                   9821:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9822:                                                  $origstart,$selfenroll,$context);
                   9823:             }
1.1172.2.9  raeburn  9824:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9825:                            $selfenroll,$context);
                   9826:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9827:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9828:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9829:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9830:                            $context);
                   9831:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9832:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9833:                              $context);
                   9834:         }
1.1053    raeburn  9835:         if ($role eq 'cc') {
                   9836:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9837:         }
1.349     www      9838:     }
                   9839:     return $answer;
1.169     harris41 9840: }
                   9841: 
1.1053    raeburn  9842: sub autoupdate_coowners {
                   9843:     my ($url,$end,$start,$uname,$udom) = @_;
                   9844:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9845:     if (($cdom ne '') && ($cnum ne '')) {
                   9846:         my $now = time;
                   9847:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9848:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9849:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9850:             my $instcode = $coursehash{'internal.coursecode'};
                   9851:             if ($instcode ne '') {
1.1056    raeburn  9852:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9853:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9854:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9855:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9856:                         if ($result eq 'valid') {
                   9857:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9858:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9859:                                     push(@newcoowners,$coowner);
                   9860:                                 }
                   9861:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9862:                                     push(@newcoowners,$uname.':'.$udom);
                   9863:                                 }
                   9864:                                 @newcoowners = sort(@newcoowners);
                   9865:                             } else {
                   9866:                                 push(@newcoowners,$uname.':'.$udom);
                   9867:                             }
                   9868:                         } else {
                   9869:                             if ($coursehash{'internal.co-owners'}) {
                   9870:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9871:                                     unless ($coowner eq $uname.':'.$udom) {
                   9872:                                         push(@newcoowners,$coowner);
                   9873:                                     }
                   9874:                                 }
                   9875:                                 unless (@newcoowners > 0) {
                   9876:                                     $delcoowners = 1;
                   9877:                                     $coowners = '';
                   9878:                                 }
                   9879:                             }
                   9880:                         }
                   9881:                         if (@newcoowners || $delcoowners) {
                   9882:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9883:                                             $delcoowners,@newcoowners);
                   9884:                         }
                   9885:                     }
                   9886:                 }
                   9887:             }
                   9888:         }
                   9889:     }
                   9890: }
                   9891: 
                   9892: sub store_coowners {
                   9893:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9894:     my $cid = $cdom.'_'.$cnum;
                   9895:     my ($coowners,$delresult,$putresult);
                   9896:     if (@newcoowners) {
                   9897:         $coowners = join(',',@newcoowners);
                   9898:         my %coownershash = (
                   9899:                             'internal.co-owners' => $coowners,
                   9900:                            );
                   9901:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9902:         if ($putresult eq 'ok') {
                   9903:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9904:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9905:             }
                   9906:         }
                   9907:     }
                   9908:     if ($delcoowners) {
                   9909:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9910:         if ($delresult eq 'ok') {
                   9911:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9912:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9913:             }
                   9914:         }
                   9915:     }
                   9916:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9917:         my %crsinfo =
                   9918:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9919:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9920:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9921:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9922:         }
                   9923:     }
                   9924: }
                   9925: 
1.169     harris41 9926: # -------------------------------------------------- Modify user authentication
1.197     www      9927: # Overrides without validation
                   9928: 
1.169     harris41 9929: sub modifyuserauth {
                   9930:     my ($udom,$uname,$umode,$upass)=@_;
                   9931:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9932:     my $allowed;
                   9933:     if (&allowed('mau',$udom)) {
                   9934:         $allowed = 1;
                   9935:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9936:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9937:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9938:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9939:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9940:         if (($cdom ne '') && ($cnum ne '')) {
                   9941:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9942:             if ($is_owner) {
                   9943:                 $allowed = 1;
                   9944:             }
                   9945:         }
                   9946:     }
                   9947:     unless ($allowed) { return 'refused'; }
1.197     www      9948:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9949:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9950:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9951:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9952: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  9953:     my $ip = &get_requestor_ip();
1.620     albertel 9954:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9955:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  9956:          '(Remote '.$ip.'): '.$reply);
1.197     www      9957:     &log($udom,,$uname,$uhome,
1.620     albertel 9958:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9959:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  9960:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 9961:     unless ($reply eq 'ok') {
1.197     www      9962:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9963: 	return 'error: '.$reply;
                   9964:     }   
1.170     harris41 9965:     return 'ok';
1.80      www      9966: }
                   9967: 
1.81      www      9968: # --------------------------------------------------------------- Modify a user
1.80      www      9969: 
1.81      www      9970: sub modifyuser {
1.206     matthew  9971:     my ($udom,    $uname, $uid,
                   9972:         $umode,   $upass, $first,
                   9973:         $middle,  $last,  $gene,
1.1058    raeburn  9974:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9975:     $udom= &LONCAPA::clean_domain($udom);
                   9976:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9977:     my $showcandelete = 'none';
                   9978:     if (ref($candelete) eq 'ARRAY') {
                   9979:         if (@{$candelete} > 0) {
                   9980:             $showcandelete = join(', ',@{$candelete});
                   9981:         }
                   9982:     }
1.81      www      9983:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9984:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9985: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9986:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9987:                                      ' desiredhome not specified'). 
1.620     albertel 9988:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9989:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9990:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9991:     my $newuser;
                   9992:     if ($uhome eq 'no_host') {
                   9993:         $newuser = 1;
                   9994:     }
1.80      www      9995: # ----------------------------------------------------------------- Create User
1.406     albertel 9996:     if (($uhome eq 'no_host') && 
                   9997: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9998:         my $unhome='';
1.844     albertel 9999:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10000:             $unhome = $desiredhome;
1.620     albertel 10001: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10002: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10003:         } else { # load balancing routine for determining $unhome
1.81      www      10004:             my $loadm=10000000;
1.841     albertel 10005: 	    my %servers = &get_servers($udom,'library');
                   10006: 	    foreach my $tryserver (keys(%servers)) {
                   10007: 		my $answer=reply('load',$tryserver);
                   10008: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10009: 		    $loadm=$answer;
                   10010: 		    $unhome=$tryserver;
                   10011: 		}
1.80      www      10012: 	    }
                   10013:         }
                   10014:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10015: 	    return 'error: unable to find a home server for '.$uname.
                   10016:                    ' in domain '.$udom;
1.80      www      10017:         }
                   10018:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10019:                          &escape($upass),$unhome);
                   10020: 	unless ($reply eq 'ok') {
                   10021:             return 'error: '.$reply;
                   10022:         }   
1.230     stredwic 10023:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10024:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10025: 	    return 'error: unable verify users home machine.';
1.80      www      10026:         }
1.209     matthew  10027:     }   # End of creation of new user
1.80      www      10028: # ---------------------------------------------------------------------- Add ID
                   10029:     if ($uid) {
                   10030:        $uid=~tr/A-Z/a-z/;
                   10031:        my %uidhash=&idrget($udom,$uname);
1.196     www      10032:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10033:          && (!$forceid)) {
1.80      www      10034: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10035: 	      return 'error: user id "'.$uid.'" does not match '.
                   10036:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10037:           }
                   10038:        } else {
                   10039: 	  &idput($udom,($uname => $uid));
                   10040:        }
                   10041:     }
                   10042: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10043:     my @tmp=&get('environment',
1.899     raeburn  10044: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10045:                     'permanentemail','inststatus'],
1.134     albertel 10046: 		   $udom,$uname);
1.1075    raeburn  10047:     my (%names,%oldnames);
1.313     matthew  10048:     if ($tmp[0] =~ m/^error:.*/) { 
                   10049:         %names=(); 
                   10050:     } else {
                   10051:         %names = @tmp;
1.1075    raeburn  10052:         %oldnames = %names;
1.313     matthew  10053:     }
1.388     www      10054: #
1.1058    raeburn  10055: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10056: # of users did not contain them), do not overwrite existing values
                   10057: # unless field is in $candelete array ref.  
                   10058: #
                   10059: 
                   10060:     my @fields = ('firstname','middlename','lastname','generation',
                   10061:                   'permanentemail','id');
                   10062:     my %newvalues;
                   10063:     if (ref($candelete) eq 'ARRAY') {
                   10064:         foreach my $field (@fields) {
                   10065:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10066:                 if ($field eq 'firstname') {
                   10067:                     $names{$field} = $first;
                   10068:                 } elsif ($field eq 'middlename') {
                   10069:                     $names{$field} = $middle;
                   10070:                 } elsif ($field eq 'lastname') {
                   10071:                     $names{$field} = $last;
                   10072:                 } elsif ($field eq 'generation') { 
                   10073:                     $names{$field} = $gene;
                   10074:                 } elsif ($field eq 'permanentemail') {
                   10075:                     $names{$field} = $email;
                   10076:                 } elsif ($field eq 'id') {
                   10077:                     $names{$field}  = $uid;
                   10078:                 }
                   10079:             }
                   10080:         }
                   10081:     }
1.388     www      10082:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10083:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10084:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10085:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10086:     if ($email) {
                   10087:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10088:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10089:     }
1.899     raeburn  10090:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10091:     if (defined($inststatus)) {
                   10092:         $names{'inststatus'} = '';
                   10093:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10094:         if (ref($usertypes) eq 'HASH') {
                   10095:             my @okstatuses; 
                   10096:             foreach my $item (split(/:/,$inststatus)) {
                   10097:                 if (defined($usertypes->{$item})) {
                   10098:                     push(@okstatuses,$item);  
                   10099:                 }
                   10100:             }
                   10101:             if (@okstatuses) {
                   10102:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10103:             }
                   10104:         }
                   10105:     }
1.1075    raeburn  10106:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10107:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10108:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10109:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10110:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10111:     } else {
                   10112:         $logmsg .= ' during self creation';
                   10113:     }
1.1075    raeburn  10114:     my $changed;
                   10115:     if ($newuser) {
                   10116:         $changed = 1;
                   10117:     } else {
                   10118:         foreach my $field (@fields) {
                   10119:             if ($names{$field} ne $oldnames{$field}) {
                   10120:                 $changed = 1;
                   10121:                 last;
                   10122:             }
                   10123:         }
                   10124:     }
                   10125:     unless ($changed) {
                   10126:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10127:         &logthis($logmsg);
                   10128:         return 'ok';
                   10129:     }
                   10130:     my $reply = &put('environment', \%names, $udom,$uname);
                   10131:     if ($reply ne 'ok') { 
                   10132:         return 'error: '.$reply;
                   10133:     }
1.1087    raeburn  10134:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10135:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10136:     }
1.1075    raeburn  10137:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10138:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10139:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10140:     &logthis($logmsg);
1.134     albertel 10141:     return 'ok';
1.80      www      10142: }
                   10143: 
1.81      www      10144: # -------------------------------------------------------------- Modify student
1.80      www      10145: 
1.81      www      10146: sub modifystudent {
                   10147:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10148:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10149:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10150:     if (!$cid) {
1.620     albertel 10151: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10152: 	    return 'not_in_class';
                   10153: 	}
1.80      www      10154:     }
                   10155: # --------------------------------------------------------------- Make the user
1.81      www      10156:     my $reply=&modifyuser
1.209     matthew  10157: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10158:          $desiredhome,$email,$inststatus);
1.80      www      10159:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10160:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10161:     # student's environment
1.297     matthew  10162:     $uid = undef if (!$forceid);
1.455     albertel 10163:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10164: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10165:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10166:     return $reply;
                   10167: }
                   10168: 
                   10169: sub modify_student_enrollment {
1.1172.2.23  raeburn  10170:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10171:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10172:     my ($cdom,$cnum,$chome);
                   10173:     if (!$cid) {
1.620     albertel 10174: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10175: 	    return 'not_in_class';
                   10176: 	}
1.620     albertel 10177: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10178: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10179:     } else {
                   10180: 	($cdom,$cnum)=split(/_/,$cid);
                   10181:     }
1.620     albertel 10182:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10183:     if (!$chome) {
1.457     raeburn  10184: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10185:     }
1.455     albertel 10186:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10187:     # Make sure the user exists
1.81      www      10188:     my $uhome=&homeserver($uname,$udom);
                   10189:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10190: 	return 'error: no such user';
                   10191:     }
1.297     matthew  10192:     # Get student data if we were not given enough information
                   10193:     if (!defined($first)  || $first  eq '' || 
                   10194:         !defined($last)   || $last   eq '' || 
                   10195:         !defined($uid)    || $uid    eq '' || 
                   10196:         !defined($middle) || $middle eq '' || 
                   10197:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10198:         # They did not supply us with enough data to enroll the student, so
                   10199:         # we need to pick up more information.
1.297     matthew  10200:         my %tmp = &get('environment',
1.294     matthew  10201:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10202:                        ,$udom,$uname);
                   10203: 
1.800     albertel 10204:         #foreach my $key (keys(%tmp)) {
                   10205:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10206:         #}
1.294     matthew  10207:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10208:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10209:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10210:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10211:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10212:     }
1.556     albertel 10213:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10214:     my $user = "$uname:$udom";
                   10215:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10216:     my $reply=cput('classlist',
1.1148    raeburn  10217: 		   {$user => 
1.1172.2.76  raeburn  10218: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10219: 		   $cdom,$cnum);
1.1148    raeburn  10220:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10221:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10222:     } else { 
1.81      www      10223: 	return 'error: '.$reply;
                   10224:     }
1.297     matthew  10225:     # Add student role to user
1.83      www      10226:     my $uurl='/'.$cid;
1.81      www      10227:     $uurl=~s/\_/\//g;
                   10228:     if ($usec) {
                   10229: 	$uurl.='/'.$usec;
                   10230:     }
1.1148    raeburn  10231:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10232:                              $selfenroll,$context);
                   10233:     if ($result ne 'ok') {
                   10234:         if ($old_entry{$user} ne '') {
                   10235:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10236:         } else {
                   10237:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10238:         }
                   10239:     }
                   10240:     return $result; 
1.21      www      10241: }
                   10242: 
1.556     albertel 10243: sub format_name {
                   10244:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10245:     my $name;
                   10246:     if ($first ne 'lastname') {
                   10247: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10248:     } else {
                   10249: 	if ($lastname=~/\S/) {
                   10250: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10251: 	    $name=~s/\s+,/,/;
                   10252: 	} else {
                   10253: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10254: 	}
                   10255:     }
                   10256:     $name=~s/^\s+//;
                   10257:     $name=~s/\s+$//;
                   10258:     $name=~s/\s+/ /g;
                   10259:     return $name;
                   10260: }
                   10261: 
1.84      www      10262: # ------------------------------------------------- Write to course preferences
                   10263: 
                   10264: sub writecoursepref {
                   10265:     my ($courseid,%prefs)=@_;
                   10266:     $courseid=~s/^\///;
                   10267:     $courseid=~s/\_/\//g;
                   10268:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10269:     my $chome=homeserver($cnum,$cdomain);
                   10270:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10271: 	return 'error: no such course';
                   10272:     }
                   10273:     my $cstring='';
1.800     albertel 10274:     foreach my $pref (keys(%prefs)) {
                   10275: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10276:     }
1.84      www      10277:     $cstring=~s/\&$//;
                   10278:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10279: }
                   10280: 
                   10281: # ---------------------------------------------------------- Make/modify course
                   10282: 
                   10283: sub createcourse {
1.741     raeburn  10284:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10285:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10286:     $url=&declutter($url);
                   10287:     my $cid='';
1.1028    raeburn  10288:     if ($context eq 'requestcourses') {
                   10289:         my $can_create = 0;
                   10290:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10291:         if ($udom eq $ownerdom) {
                   10292:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10293:                                   $context)) {
                   10294:                 $can_create = 1;
                   10295:             }
                   10296:         } else {
                   10297:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10298:                                            $category);
                   10299:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10300:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10301:                 if (@curr > 0) {
                   10302:                     my @options = qw(approval validate autolimit);
                   10303:                     my $optregex = join('|',@options);
                   10304:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10305:                         $can_create = 1;
                   10306:                     }
                   10307:                 }
                   10308:             }
                   10309:         }
                   10310:         if ($can_create) {
                   10311:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10312:                 unless (&allowed('ccc',$udom)) {
                   10313:                     return 'refused'; 
                   10314:                 }
1.1017    raeburn  10315:             }
                   10316:         } else {
                   10317:             return 'refused';
                   10318:         }
1.1028    raeburn  10319:     } elsif (!&allowed('ccc',$udom)) {
                   10320:         return 'refused';
1.84      www      10321:     }
1.1011    raeburn  10322: # --------------------------------------------------------------- Get Unique ID
                   10323:     my $uname;
                   10324:     if ($cnum =~ /^$match_courseid$/) {
                   10325:         my $chome=&homeserver($cnum,$udom,'true');
                   10326:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10327:             $uname = $cnum;
                   10328:         } else {
1.1038    raeburn  10329:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10330:         }
                   10331:     } else {
1.1038    raeburn  10332:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10333:     }
                   10334:     return $uname if ($uname =~ /^error/);
                   10335: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10336:     if (!defined($course_server)) {
                   10337:         if (defined(&domain($udom,'primary'))) {
                   10338:             $course_server = &domain($udom,'primary');
                   10339:         } else {
                   10340:             $course_server = $env{'user.home'}; 
                   10341:         }
                   10342:     }
                   10343:     my %host_servers =
                   10344:         &Apache::lonnet::get_servers($udom,'library');
                   10345:     unless ($host_servers{$course_server}) {
                   10346:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10347:     }
1.84      www      10348: # ------------------------------------------------------------- Make the course
                   10349:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10350:                       $course_server);
1.84      www      10351:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10352:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10353:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10354: 	return 'error: no such course';
                   10355:     }
1.271     www      10356: # ----------------------------------------------------------------- Course made
1.516     raeburn  10357: # log existence
1.1029    raeburn  10358:     my $now = time;
1.918     raeburn  10359:     my $newcourse = {
                   10360:                     $udom.'_'.$uname => {
1.921     raeburn  10361:                                      description => $description,
                   10362:                                      inst_code   => $inst_code,
                   10363:                                      owner       => $course_owner,
                   10364:                                      type        => $crstype,
1.1029    raeburn  10365:                                      creator     => $env{'user.name'}.':'.
                   10366:                                                     $env{'user.domain'},
                   10367:                                      created     => $now,
                   10368:                                      context     => $context,
1.918     raeburn  10369:                                                 },
                   10370:                     };
1.921     raeburn  10371:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10372: # set toplevel url
1.271     www      10373:     my $topurl=$url;
                   10374:     unless ($nonstandard) {
                   10375: # ------------------------------------------ For standard courses, make top url
                   10376:         my $mapurl=&clutter($url);
1.278     www      10377:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10378:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10379: <map>
                   10380: <resource id="1" type="start"></resource>
                   10381: <resource id="2" src="$mapurl"></resource>
                   10382: <resource id="3" type="finish"></resource>
                   10383: <link index="1" from="1" to="2"></link>
                   10384: <link index="2" from="2" to="3"></link>
                   10385: </map>
                   10386: ENDINITMAP
                   10387:         $topurl=&declutter(
1.638     albertel 10388:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10389:                           );
                   10390:     }
                   10391: # ----------------------------------------------------------- Write preferences
1.84      www      10392:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10393:                      ('description'              => $description,
                   10394:                       'url'                      => $topurl,
                   10395:                       'internal.creator'         => $env{'user.name'}.':'.
                   10396:                                                     $env{'user.domain'},
                   10397:                       'internal.created'         => $now,
                   10398:                       'internal.creationcontext' => $context)
                   10399:                     );
1.84      www      10400:     return '/'.$udom.'/'.$uname;
                   10401: }
                   10402: 
1.1011    raeburn  10403: # ------------------------------------------------------------------- Create ID
                   10404: sub generate_coursenum {
1.1038    raeburn  10405:     my ($udom,$crstype) = @_;
1.1011    raeburn  10406:     my $domdesc = &domain($udom);
                   10407:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10408:     my $first;
                   10409:     if ($crstype eq 'Community') {
                   10410:         $first = '0';
                   10411:     } else {
                   10412:         $first = int(1+rand(9)); 
                   10413:     } 
                   10414:     my $uname=$first.
1.1011    raeburn  10415:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10416:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10417:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10418: # ----------------------------------------------- Make sure that does not exist
                   10419:     my $uhome=&homeserver($uname,$udom,'true');
                   10420:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10421:         if ($crstype eq 'Community') {
                   10422:             $first = '0';
                   10423:         } else {
                   10424:             $first = int(1+rand(9));
                   10425:         }
                   10426:         $uname=$first.
1.1011    raeburn  10427:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10428:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10429:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10430:         $uhome=&homeserver($uname,$udom,'true');
                   10431:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10432:             return 'error: unable to generate unique course-ID';
                   10433:         }
                   10434:     }
                   10435:     return $uname;
                   10436: }
                   10437: 
1.813     albertel 10438: sub is_course {
1.1167    droeschl 10439:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10440:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10441:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10442:     my $uhome=&homeserver($cnum,$cdom);
                   10443:     my $iscourse;
                   10444:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10445:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10446:     } else {
                   10447:         my $hashid = $cdom.':'.$cnum;
                   10448:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10449:         unless (defined($cached)) {
                   10450:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10451:                                         $cnum,undef,undef,'.');
                   10452:             $iscourse = 0;
                   10453:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10454:                 $iscourse = 1;
                   10455:             }
                   10456:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10457:         }
                   10458:     }
                   10459:     return unless($iscourse);
1.1167    droeschl 10460:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10461: }
                   10462: 
1.1015    raeburn  10463: sub store_userdata {
                   10464:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10465:     my $result;
1.1016    raeburn  10466:     if ($datakey ne '') {
1.1013    raeburn  10467:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10468:             if ($udom eq '' || $uname eq '') {
                   10469:                 $udom = $env{'user.domain'};
                   10470:                 $uname = $env{'user.name'};
                   10471:             }
                   10472:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10473:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10474:                 $result = 'error: no_host';
                   10475:             } else {
                   10476:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10477:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10478: 
                   10479:                 my $namevalue='';
                   10480:                 foreach my $key (keys(%{$storehash})) {
                   10481:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10482:                 }
                   10483:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10484:                 unless ($namespace eq 'courserequests') {
                   10485:                     $datakey = &escape($datakey);
                   10486:                 }
1.1105    raeburn  10487:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10488:                                   $namevalue,$uhome);
1.1013    raeburn  10489:             }
                   10490:         } else {
                   10491:             $result = 'error: data to store was not a hash reference'; 
                   10492:         }
                   10493:     } else {
                   10494:         $result= 'error: invalid requestkey'; 
                   10495:     }
                   10496:     return $result;
                   10497: }
                   10498: 
1.21      www      10499: # ---------------------------------------------------------- Assign Custom Role
                   10500: 
                   10501: sub assigncustomrole {
1.957     raeburn  10502:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10503:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10504:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10505: }
                   10506: 
                   10507: # ----------------------------------------------------------------- Revoke Role
                   10508: 
                   10509: sub revokerole {
1.957     raeburn  10510:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10511:     my $now=time;
1.965     raeburn  10512:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10513: }
                   10514: 
                   10515: # ---------------------------------------------------------- Revoke Custom Role
                   10516: 
                   10517: sub revokecustomrole {
1.957     raeburn  10518:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10519:     my $now=time;
1.357     www      10520:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10521:            $deleteflag,$selfenroll,$context);
1.17      www      10522: }
                   10523: 
1.533     banghart 10524: # ------------------------------------------------------------ Disk usage
1.535     albertel 10525: sub diskusage {
1.955     raeburn  10526:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10527:     $directorypath =~ s/\/$//;
                   10528:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10529:                        .&escape($getpropath).':'.&escape($uname).':'
                   10530:                        .&escape($udom),homeserver($uname,$udom));
                   10531:     if ($listing eq 'unknown_cmd') {
                   10532:         if ($getpropath) {
                   10533:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10534:         }
                   10535:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10536:     }
1.514     albertel 10537:     return $listing;
1.512     banghart 10538: }
                   10539: 
1.566     banghart 10540: sub is_locked {
1.1096    raeburn  10541:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10542:     my @check;
                   10543:     my $is_locked;
1.1093    raeburn  10544:     push (@check,$file_name);
1.613     albertel 10545:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10546: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10547:     my ($tmp)=keys(%locked);
                   10548:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10549:     
1.566     banghart 10550:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10551:         $is_locked = 'false';
                   10552:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10553:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10554:                $is_locked = 'true';
1.1096    raeburn  10555:                if (ref($which) eq 'ARRAY') {
                   10556:                    push(@{$which},$entry);
                   10557:                } else {
                   10558:                    last;
                   10559:                }
1.745     raeburn  10560:            }
                   10561:        }
1.566     banghart 10562:     } else {
                   10563:         $is_locked = 'false';
                   10564:     }
1.1093    raeburn  10565:     return $is_locked;
1.566     banghart 10566: }
                   10567: 
1.759     albertel 10568: sub declutter_portfile {
                   10569:     my ($file) = @_;
1.833     albertel 10570:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10571:     return $file;
                   10572: }
                   10573: 
1.559     banghart 10574: # ------------------------------------------------------------- Mark as Read Only
                   10575: 
                   10576: sub mark_as_readonly {
                   10577:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10578:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10579:     my ($tmp)=keys(%current_permissions);
                   10580:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10581:     foreach my $file (@{$files}) {
1.759     albertel 10582: 	$file = &declutter_portfile($file);
1.561     banghart 10583:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10584:     }
1.613     albertel 10585:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10586:     return;
                   10587: }
                   10588: 
1.572     banghart 10589: # ------------------------------------------------------------Save Selected Files
                   10590: 
                   10591: sub save_selected_files {
                   10592:     my ($user, $path, @files) = @_;
                   10593:     my $filename = $user."savedfiles";
1.573     banghart 10594:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10595:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10596:     foreach my $file (@files) {
1.620     albertel 10597:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10598:     }
                   10599:     foreach my $file (@other_files) {
1.574     banghart 10600:         print (OUT $file."\n");
1.572     banghart 10601:     }
1.574     banghart 10602:     close (OUT);
1.572     banghart 10603:     return 'ok';
                   10604: }
                   10605: 
1.574     banghart 10606: sub clear_selected_files {
                   10607:     my ($user) = @_;
                   10608:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10609:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10610:     print (OUT undef);
                   10611:     close (OUT);
                   10612:     return ("ok");    
                   10613: }
                   10614: 
1.572     banghart 10615: sub files_in_path {
                   10616:     my ($user, $path) = @_;
                   10617:     my $filename = $user."savedfiles";
                   10618:     my %return_files;
1.1172.2.96  raeburn  10619:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10620:     while (my $line_in = <IN>) {
1.574     banghart 10621:         chomp ($line_in);
                   10622:         my @paths_and_file = split (m!/!, $line_in);
                   10623:         my $file_part = pop (@paths_and_file);
                   10624:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10625:         $path_part.='/';
                   10626:         my $path_and_file = $path_part.$file_part;
                   10627:         if ($path_part eq $path) {
                   10628:             $return_files{$file_part}= 'selected';
                   10629:         }
                   10630:     }
1.574     banghart 10631:     close (IN);
                   10632:     return (\%return_files);
1.572     banghart 10633: }
                   10634: 
                   10635: # called in portfolio select mode, to show files selected NOT in current directory
                   10636: sub files_not_in_path {
                   10637:     my ($user, $path) = @_;
                   10638:     my $filename = $user."savedfiles";
                   10639:     my @return_files;
                   10640:     my $path_part;
1.1172.2.96  raeburn  10641:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10642:     while (my $line = <IN>) {
1.572     banghart 10643:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10644:         my @paths_and_file = split(m|/|, $line);
                   10645:         my $file_part = pop(@paths_and_file);
                   10646:         chomp($file_part);
                   10647:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10648:         $path_part .= '/';
                   10649:         my $path_and_file = $path_part.$file_part;
                   10650:         if ($path_part ne $path) {
1.800     albertel 10651:             push(@return_files, ($path_and_file));
1.572     banghart 10652:         }
                   10653:     }
1.800     albertel 10654:     close(OUT);
1.574     banghart 10655:     return (@return_files);
1.572     banghart 10656: }
                   10657: 
1.745     raeburn  10658: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10659: 
1.745     raeburn  10660: sub get_portfile_permissions {
                   10661:     my ($domain,$user) = @_;
1.613     albertel 10662:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10663:     my ($tmp)=keys(%current_permissions);
                   10664:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10665:     return \%current_permissions;
                   10666: }
                   10667: 
                   10668: #---------------------------------------------Get portfolio file access controls
                   10669: 
1.749     raeburn  10670: sub get_access_controls {
1.745     raeburn  10671:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10672:     my %access;
                   10673:     my $real_file = $file;
                   10674:     $file =~ s/\.meta$//;
1.745     raeburn  10675:     if (defined($file)) {
1.749     raeburn  10676:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10677:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10678:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10679:             }
                   10680:         }
1.745     raeburn  10681:     } else {
1.749     raeburn  10682:         foreach my $key (keys(%{$current_permissions})) {
                   10683:             if ($key =~ /\0accesscontrol$/) {
                   10684:                 if (defined($group)) {
                   10685:                     if ($key !~ m-^\Q$group\E/-) {
                   10686:                         next;
                   10687:                     }
                   10688:                 }
                   10689:                 my ($fullpath) = split(/\0/,$key);
                   10690:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10691:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10692:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10693:                     }
                   10694:                 }
                   10695:             }
                   10696:         }
                   10697:     }
                   10698:     return %access;
                   10699: }
                   10700: 
                   10701: sub modify_access_controls {
                   10702:     my ($file_name,$changes,$domain,$user)=@_;
                   10703:     my ($outcome,$deloutcome);
                   10704:     my %store_permissions;
                   10705:     my %new_values;
                   10706:     my %new_control;
                   10707:     my %translation;
                   10708:     my @deletions = ();
                   10709:     my $now = time;
                   10710:     if (exists($$changes{'activate'})) {
                   10711:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10712:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10713:             my $numnew = scalar(@newitems);
                   10714:             for (my $i=0; $i<$numnew; $i++) {
                   10715:                 my $newkey = $newitems[$i];
                   10716:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10717:                 if ($newkey =~ /^\d+:/) { 
                   10718:                     $newkey =~ s/^(\d+)/$newid/;
                   10719:                     $translation{$1} = $newid;
                   10720:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10721:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10722:                     $translation{$1} = $newid;
                   10723:                 }
1.749     raeburn  10724:                 $new_values{$file_name."\0".$newkey} = 
                   10725:                                           $$changes{'activate'}{$newitems[$i]};
                   10726:                 $new_control{$newkey} = $now;
                   10727:             }
                   10728:         }
                   10729:     }
                   10730:     my %todelete;
                   10731:     my %changed_items;
                   10732:     foreach my $action ('delete','update') {
                   10733:         if (exists($$changes{$action})) {
                   10734:             if (ref($$changes{$action}) eq 'HASH') {
                   10735:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10736:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10737:                     if ($action eq 'delete') { 
                   10738:                         $todelete{$itemnum} = 1;
                   10739:                     } else {
                   10740:                         $changed_items{$itemnum} = $key;
                   10741:                     }
                   10742:                 }
1.745     raeburn  10743:             }
                   10744:         }
1.749     raeburn  10745:     }
                   10746:     # get lock on access controls for file.
                   10747:     my $lockhash = {
                   10748:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10749:                                                        ':'.$env{'user.domain'},
                   10750:                    }; 
                   10751:     my $tries = 0;
                   10752:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10753:    
1.1172.2.79  raeburn  10754:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10755:         $tries ++;
1.1172.2.79  raeburn  10756:         sleep(0.1);
1.749     raeburn  10757:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10758:     }
                   10759:     if ($gotlock eq 'ok') {
                   10760:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10761:         my ($tmp)=keys(%curr_permissions);
                   10762:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10763:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10764:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10765:             if (ref($curr_controls) eq 'HASH') {
                   10766:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10767:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10768:                     if (defined($todelete{$itemnum})) {
                   10769:                         push(@deletions,$file_name."\0".$control_item);
                   10770:                     } else {
                   10771:                         if (defined($changed_items{$itemnum})) {
                   10772:                             $new_control{$changed_items{$itemnum}} = $now;
                   10773:                             push(@deletions,$file_name."\0".$control_item);
                   10774:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10775:                         } else {
                   10776:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10777:                         }
                   10778:                     }
1.745     raeburn  10779:                 }
                   10780:             }
                   10781:         }
1.970     raeburn  10782:         my ($group);
                   10783:         if (&is_course($domain,$user)) {
                   10784:             ($group,my $file) = split(/\//,$file_name,2);
                   10785:         }
1.749     raeburn  10786:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10787:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10788:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10789:         #  remove lock
                   10790:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10791:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10792:         my $sqlresult =
1.970     raeburn  10793:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10794:                                     $group);
1.749     raeburn  10795:     } else {
                   10796:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10797:     }
1.749     raeburn  10798:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10799: }
                   10800: 
1.827     raeburn  10801: sub make_public_indefinitely {
                   10802:     my ($requrl) = @_;
                   10803:     my $now = time;
                   10804:     my $action = 'activate';
                   10805:     my $aclnum = 0;
                   10806:     if (&is_portfolio_url($requrl)) {
                   10807:         my (undef,$udom,$unum,$file_name,$group) =
                   10808:             &parse_portfolio_url($requrl);
                   10809:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10810:         my %access_controls = &get_access_controls($current_perms,
                   10811:                                                    $group,$file_name);
                   10812:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10813:             my ($num,$scope,$end,$start) = 
                   10814:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10815:             if ($scope eq 'public') {
                   10816:                 if ($start <= $now && $end == 0) {
                   10817:                     $action = 'none';
                   10818:                 } else {
                   10819:                     $action = 'update';
                   10820:                     $aclnum = $num;
                   10821:                 }
                   10822:                 last;
                   10823:             }
                   10824:         }
                   10825:         if ($action eq 'none') {
                   10826:              return 'ok';
                   10827:         } else {
                   10828:             my %changes;
                   10829:             my $newend = 0;
                   10830:             my $newstart = $now;
                   10831:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10832:             $changes{$action}{$newkey} = {
                   10833:                 type => 'public',
                   10834:                 time => {
                   10835:                     start => $newstart,
                   10836:                     end   => $newend,
                   10837:                 },
                   10838:             };
                   10839:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10840:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10841:             return $outcome;
                   10842:         }
                   10843:     } else {
                   10844:         return 'invalid';
                   10845:     }
                   10846: }
                   10847: 
1.745     raeburn  10848: #------------------------------------------------------Get Marked as Read Only
                   10849: 
                   10850: sub get_marked_as_readonly {
                   10851:     my ($domain,$user,$what,$group) = @_;
                   10852:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10853:     my @readonly_files;
1.629     banghart 10854:     my $cmp1=$what;
                   10855:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10856:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10857:         if (defined($group)) {
                   10858:             if ($file_name !~ m-^\Q$group\E/-) {
                   10859:                 next;
                   10860:             }
                   10861:         }
1.561     banghart 10862:         if (ref($value) eq "ARRAY"){
                   10863:             foreach my $stored_what (@{$value}) {
1.629     banghart 10864:                 my $cmp2=$stored_what;
1.759     albertel 10865:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10866:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10867:                 }
1.629     banghart 10868:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10869:                     push(@readonly_files, $file_name);
1.745     raeburn  10870:                     last;
1.563     banghart 10871:                 } elsif (!defined($what)) {
                   10872:                     push(@readonly_files, $file_name);
1.745     raeburn  10873:                     last;
1.561     banghart 10874:                 }
                   10875:             }
1.745     raeburn  10876:         }
1.561     banghart 10877:     }
                   10878:     return @readonly_files;
                   10879: }
1.577     banghart 10880: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10881: 
1.577     banghart 10882: sub get_marked_as_readonly_hash {
1.745     raeburn  10883:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10884:     my %readonly_files;
1.745     raeburn  10885:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10886:         if (defined($group)) {
                   10887:             if ($file_name !~ m-^\Q$group\E/-) {
                   10888:                 next;
                   10889:             }
                   10890:         }
1.577     banghart 10891:         if (ref($value) eq "ARRAY"){
                   10892:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10893:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10894:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10895:                         if ($lock_descriptor eq 'graded') {
                   10896:                             $readonly_files{$file_name} = 'graded';
                   10897:                         } elsif ($lock_descriptor eq 'handback') {
                   10898:                             $readonly_files{$file_name} = 'handback';
                   10899:                         } else {
                   10900:                             if (!exists($readonly_files{$file_name})) {
                   10901:                                 $readonly_files{$file_name} = 'locked';
                   10902:                             }
                   10903:                         }
1.745     raeburn  10904:                     }
1.750     banghart 10905:                 } 
1.577     banghart 10906:             }
                   10907:         } 
                   10908:     }
                   10909:     return %readonly_files;
                   10910: }
1.559     banghart 10911: # ------------------------------------------------------------ Unmark as Read Only
                   10912: 
                   10913: sub unmark_as_readonly {
1.629     banghart 10914:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10915:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10916:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10917:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10918:     my $symb_crs = $what;
                   10919:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10920:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10921:     my ($tmp)=keys(%current_permissions);
                   10922:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10923:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10924:     foreach my $file (@readonly_files) {
1.759     albertel 10925: 	my $clean_file = &declutter_portfile($file);
                   10926: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10927: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10928:         my @new_locks;
                   10929:         my @del_keys;
                   10930:         if (ref($current_locks) eq "ARRAY"){
                   10931:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10932:                 my $compare=$locker;
1.749     raeburn  10933:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10934:                     $compare=join('',@{$locker});
1.746     raeburn  10935:                     if ($compare ne $symb_crs) {
                   10936:                         push(@new_locks, $locker);
                   10937:                     }
1.563     banghart 10938:                 }
                   10939:             }
1.650     albertel 10940:             if (scalar(@new_locks) > 0) {
1.563     banghart 10941:                 $current_permissions{$file} = \@new_locks;
                   10942:             } else {
                   10943:                 push(@del_keys, $file);
1.613     albertel 10944:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10945:                 delete($current_permissions{$file});
1.563     banghart 10946:             }
                   10947:         }
1.561     banghart 10948:     }
1.613     albertel 10949:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10950:     return;
                   10951: }
1.512     banghart 10952: 
1.17      www      10953: # ------------------------------------------------------------ Directory lister
                   10954: 
                   10955: sub dirlist {
1.955     raeburn  10956:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10957:     $uri=~s/^\///;
                   10958:     $uri=~s/\/$//;
1.253     stredwic 10959:     my ($udom, $uname);
1.955     raeburn  10960:     if ($getuserdir) {
1.253     stredwic 10961:         $udom = $userdomain;
                   10962:         $uname = $username;
1.955     raeburn  10963:     } else {
                   10964:         (undef,$udom,$uname)=split(/\//,$uri);
                   10965:         if(defined($userdomain)) {
                   10966:             $udom = $userdomain;
                   10967:         }
                   10968:         if(defined($username)) {
                   10969:             $uname = $username;
                   10970:         }
1.253     stredwic 10971:     }
1.955     raeburn  10972:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10973: 
1.955     raeburn  10974:     $dirRoot = $perlvar{'lonDocRoot'};
                   10975:     if (defined($getpropath)) {
                   10976:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10977:         $dirRoot =~ s/\/$//;
1.955     raeburn  10978:     } elsif (defined($getuserdir)) {
                   10979:         my $subdir=$uname.'__';
                   10980:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10981:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10982:                    ."/$udom/$subdir/$uname";
                   10983:     } elsif (defined($alternateRoot)) {
                   10984:         $dirRoot = $alternateRoot;
1.751     banghart 10985:     }
1.253     stredwic 10986: 
                   10987:     if($udom) {
                   10988:         if($uname) {
1.1135    raeburn  10989:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10990:             if ($uhome eq 'no_host') {
                   10991:                 return ([],'no_host');
                   10992:             }
1.955     raeburn  10993:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10994:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10995:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10996:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10997:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10998:             } else {
                   10999:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11000:             }
1.605     matthew  11001:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11002:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11003:                 @listing_results = split(/:/,$listing);
                   11004:             } else {
                   11005:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11006:             }
1.1135    raeburn  11007:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11008:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11009:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11010:                 return ([],$listing);
                   11011:             } else {
                   11012:                 return (\@listing_results);
1.1135    raeburn  11013:             }
1.955     raeburn  11014:         } elsif(!$alternateRoot) {
1.1136    raeburn  11015:             my (%allusers,%listerror);
1.841     albertel 11016: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11017:  	    foreach my $tryserver (keys(%servers)) {
                   11018:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11019:                                   &escape($udom),$tryserver);
                   11020:                 if ($listing eq 'unknown_cmd') {
                   11021: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11022: 				      $udom, $tryserver);
                   11023:                 } else {
                   11024:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11025:                 }
1.841     albertel 11026: 		if ($listing eq 'unknown_cmd') {
                   11027: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11028: 				      $udom, $tryserver);
                   11029: 		    @listing_results = split(/:/,$listing);
                   11030: 		} else {
                   11031: 		    @listing_results =
                   11032: 			map { &unescape($_); } split(/:/,$listing);
                   11033: 		}
1.1136    raeburn  11034:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11035:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11036:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11037:                     $listerror{$tryserver} = $listing;
                   11038:                 } else {
1.841     albertel 11039: 		    foreach my $line (@listing_results) {
                   11040: 			my ($entry) = split(/&/,$line,2);
                   11041: 			$allusers{$entry} = 1;
                   11042: 		    }
                   11043: 		}
1.253     stredwic 11044:             }
1.1136    raeburn  11045:             my @alluserslist=();
1.800     albertel 11046:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11047:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11048:             }
1.1172.2.80  raeburn  11049:             if (!%listerror) {
                   11050:                 # no errors
                   11051:                 return (\@alluserslist);
                   11052:             } elsif (scalar(keys(%servers)) == 1) {
                   11053:                 # one library server, one error
                   11054:                 my ($key) = keys(%listerror);
                   11055:                 return (\@alluserslist, $listerror{$key});
                   11056:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11057:                 # con_lost indicates that we might miss data from at least one
                   11058:                 # library server
                   11059:                 return (\@alluserslist, 'con_lost');
                   11060:             } else {
                   11061:                 # multiple library servers and no con_lost -> data should be
                   11062:                 # complete.
                   11063:                 return (\@alluserslist);
                   11064:             }
                   11065: 
1.253     stredwic 11066:         } else {
1.1136    raeburn  11067:             return ([],'missing username');
1.253     stredwic 11068:         }
1.955     raeburn  11069:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11070:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11071:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11072:         return (\@all_domains);
1.955     raeburn  11073:     } else {
1.1136    raeburn  11074:         return ([],'missing domain');
1.275     stredwic 11075:     }
                   11076: }
                   11077: 
                   11078: # --------------------------------------------- GetFileTimestamp
                   11079: # This function utilizes dirlist and returns the date stamp for
                   11080: # when it was last modified.  It will also return an error of -1
                   11081: # if an error occurs
                   11082: 
                   11083: sub GetFileTimestamp {
1.955     raeburn  11084:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11085:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11086:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11087:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11088:                                     undef,$getuserdir);
                   11089:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11090:         return -1;
                   11091:     }
                   11092:     if (ref($fileref) eq 'ARRAY') {
                   11093:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11094:         # @stats contains first the filename, then the stat output
                   11095:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11096:     } else {
                   11097:         return -1;
1.253     stredwic 11098:     }
1.26      www      11099: }
                   11100: 
1.712     albertel 11101: sub stat_file {
                   11102:     my ($uri) = @_;
1.787     albertel 11103:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11104: 
1.955     raeburn  11105:     my ($udom,$uname,$file);
1.712     albertel 11106:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11107: 	($udom,$uname,$file) =
1.811     albertel 11108: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11109: 	$file = 'userfiles/'.$file;
                   11110:     }
                   11111:     if ($uri =~ m-^/res/-) {
                   11112: 	($udom,$uname) = 
1.807     albertel 11113: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11114: 	$file = $uri;
                   11115:     }
                   11116: 
                   11117:     if (!$udom || !$uname || !$file) {
                   11118: 	# unable to handle the uri
                   11119: 	return ();
                   11120:     }
1.956     raeburn  11121:     my $getpropath;
                   11122:     if ($file =~ /^userfiles\//) {
                   11123:         $getpropath = 1;
                   11124:     }
1.1136    raeburn  11125:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11126:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11127:         return ();
                   11128:     } else {
                   11129:         if (ref($listref) eq 'ARRAY') {
                   11130:             my @stats = split('&',$listref->[0]);
                   11131: 	    shift(@stats); #filename is first
                   11132: 	    return @stats;
                   11133:         }
1.712     albertel 11134:     }
                   11135:     return ();
                   11136: }
                   11137: 
1.26      www      11138: # -------------------------------------------------------- Value of a Condition
                   11139: 
1.713     albertel 11140: # gets the value of a specific preevaluated condition
                   11141: #    stored in the string  $env{user.state.<cid>}
                   11142: # or looks up a condition reference in the bighash and if if hasn't
                   11143: # already been evaluated recurses into docondval to get the value of
                   11144: # the condition, then memoizing it to 
                   11145: #   $env{user.state.<cid>.<condition>}
1.40      www      11146: sub directcondval {
                   11147:     my $number=shift;
1.620     albertel 11148:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11149: 	&Apache::lonuserstate::evalstate();
                   11150:     }
1.713     albertel 11151:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11152: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11153:     } elsif ($number =~ /^_/) {
                   11154: 	my $sub_condition;
                   11155: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11156: 		&GDBM_READER(),0640)) {
                   11157: 	    $sub_condition=$bighash{'conditions'.$number};
                   11158: 	    untie(%bighash);
                   11159: 	}
                   11160: 	my $value = &docondval($sub_condition);
1.949     raeburn  11161: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11162: 	return $value;
                   11163:     }
1.620     albertel 11164:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11165:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11166:     } else {
                   11167:        return 2;
                   11168:     }
                   11169: }
                   11170: 
1.713     albertel 11171: # get the collection of conditions for this resource
1.26      www      11172: sub condval {
                   11173:     my $condidx=shift;
1.54      www      11174:     my $allpathcond='';
1.713     albertel 11175:     foreach my $cond (split(/\|/,$condidx)) {
                   11176: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11177: 	    $allpathcond.=
                   11178: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11179: 	}
1.191     harris41 11180:     }
1.54      www      11181:     $allpathcond=~s/\|$//;
1.713     albertel 11182:     return &docondval($allpathcond);
                   11183: }
                   11184: 
                   11185: #evaluates an expression of conditions
                   11186: sub docondval {
                   11187:     my ($allpathcond) = @_;
                   11188:     my $result=0;
                   11189:     if ($env{'request.course.id'}
                   11190: 	&& defined($allpathcond)) {
                   11191: 	my $operand='|';
                   11192: 	my @stack;
                   11193: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11194: 	    if ($chunk eq '(') {
                   11195: 		push @stack,($operand,$result);
                   11196: 	    } elsif ($chunk eq ')') {
                   11197: 		my $before=pop @stack;
                   11198: 		if (pop @stack eq '&') {
                   11199: 		    $result=$result>$before?$before:$result;
                   11200: 		} else {
                   11201: 		    $result=$result>$before?$result:$before;
                   11202: 		}
                   11203: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11204: 		$operand=$chunk;
                   11205: 	    } else {
                   11206: 		my $new=directcondval($chunk);
                   11207: 		if ($operand eq '&') {
                   11208: 		    $result=$result>$new?$new:$result;
                   11209: 		} else {
                   11210: 		    $result=$result>$new?$result:$new;
                   11211: 		}
                   11212: 	    }
                   11213: 	}
1.26      www      11214:     }
                   11215:     return $result;
1.421     albertel 11216: }
                   11217: 
                   11218: # ---------------------------------------------------- Devalidate courseresdata
                   11219: 
                   11220: sub devalidatecourseresdata {
                   11221:     my ($coursenum,$coursedomain)=@_;
                   11222:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11223:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11224: }
                   11225: 
1.763     www      11226: 
1.200     www      11227: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11228: #
                   11229: #  Parameters:
                   11230: #      $coursenum    - Number of the course.
                   11231: #      $coursedomain - Domain at which the course was created.
                   11232: #  Returns:
                   11233: #     A hash of the course parameters along (I think) with timestamps
                   11234: #     and version info.
1.877     foxr     11235: 
1.624     albertel 11236: sub get_courseresdata {
                   11237:     my ($coursenum,$coursedomain)=@_;
1.200     www      11238:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11239:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11240:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11241:     my %dumpreply;
1.417     albertel 11242:     unless (defined($cached)) {
1.624     albertel 11243: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11244: 	$result=\%dumpreply;
1.251     albertel 11245: 	my ($tmp) = keys(%dumpreply);
                   11246: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11247: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11248: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11249: 	    return $tmp;
1.416     albertel 11250: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11251: 	    $result=undef;
1.599     albertel 11252: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11253: 	}
                   11254:     }
1.624     albertel 11255:     return $result;
                   11256: }
                   11257: 
1.633     albertel 11258: sub devalidateuserresdata {
                   11259:     my ($uname,$udom)=@_;
                   11260:     my $hashid="$udom:$uname";
                   11261:     &devalidate_cache_new('userres',$hashid);
                   11262: }
                   11263: 
1.624     albertel 11264: sub get_userresdata {
                   11265:     my ($uname,$udom)=@_;
                   11266:     #most student don\'t have any data set, check if there is some data
                   11267:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11268: 
                   11269:     my $hashid="$udom:$uname";
                   11270:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11271:     if (!defined($cached)) {
                   11272: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11273: 	$result=\%resourcedata;
                   11274: 	&do_cache_new('userres',$hashid,$result,600);
                   11275:     }
                   11276:     my ($tmp)=keys(%$result);
                   11277:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11278: 	return $result;
                   11279:     }
                   11280:     #error 2 occurs when the .db doesn't exist
                   11281:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11282:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11283: 	    &logthis("<font color=\"blue\">WARNING:".
                   11284: 		     " Trying to get resource data for ".
                   11285: 		     $uname." at ".$udom.": ".
                   11286: 		     $tmp."</font>");
                   11287:         }
1.624     albertel 11288:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11289: 	#&EXT_cache_set($udom,$uname);
                   11290: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11291: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11292:     }
                   11293:     return $tmp;
                   11294: }
1.879     foxr     11295: #----------------------------------------------- resdata - return resource data
                   11296: #  Purpose:
                   11297: #    Return resource data for either users or for a course.
                   11298: #  Parameters:
                   11299: #     $name      - Course/user name.
                   11300: #     $domain    - Name of the domain the user/course is registered on.
                   11301: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11302: #     @which     - Array of names of resources desired.
                   11303: #  Returns:
                   11304: #     The value of the first reasource in @which that is found in the
                   11305: #     resource hash.
                   11306: #  Exceptional Conditions:
                   11307: #     If the $type passed in is not valid (not the string 'course' or 
                   11308: #     'user', an undefined  reference is returned.
                   11309: #     If none of the resources are found, an undef is returned
1.624     albertel 11310: sub resdata {
                   11311:     my ($name,$domain,$type,@which)=@_;
                   11312:     my $result;
                   11313:     if ($type eq 'course') {
                   11314: 	$result=&get_courseresdata($name,$domain);
                   11315:     } elsif ($type eq 'user') {
                   11316: 	$result=&get_userresdata($name,$domain);
                   11317:     }
                   11318:     if (!ref($result)) { return $result; }    
1.251     albertel 11319:     foreach my $item (@which) {
1.927     albertel 11320: 	if (defined($result->{$item->[0]})) {
                   11321: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11322: 	}
1.250     albertel 11323:     }
1.291     albertel 11324:     return undef;
1.200     www      11325: }
                   11326: 
1.1172.2.31  raeburn  11327: sub get_numsuppfiles {
                   11328:     my ($cnum,$cdom,$ignorecache)=@_;
                   11329:     my $hashid=$cnum.':'.$cdom;
                   11330:     my ($suppcount,$cached);
                   11331:     unless ($ignorecache) {
                   11332:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11333:     }
                   11334:     unless (defined($cached)) {
                   11335:         my $chome=&homeserver($cnum,$cdom);
                   11336:         unless ($chome eq 'no_host') {
                   11337:             ($suppcount,my $errors) = (0,0);
                   11338:             my $suppmap = 'supplemental.sequence';
                   11339:             ($suppcount,$errors) =
                   11340:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11341:         }
                   11342:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11343:     }
                   11344:     return $suppcount;
                   11345: }
                   11346: 
1.379     matthew  11347: #
                   11348: # EXT resource caching routines
                   11349: #
                   11350: 
                   11351: sub clear_EXT_cache_status {
1.383     albertel 11352:     &delenv('cache.EXT.');
1.379     matthew  11353: }
                   11354: 
                   11355: sub EXT_cache_status {
                   11356:     my ($target_domain,$target_user) = @_;
1.383     albertel 11357:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11358:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11359:         # We know already the user has no data
                   11360:         return 1;
                   11361:     } else {
                   11362:         return 0;
                   11363:     }
                   11364: }
                   11365: 
                   11366: sub EXT_cache_set {
                   11367:     my ($target_domain,$target_user) = @_;
1.383     albertel 11368:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11369:     #&appenv({$cachename => time});
1.379     matthew  11370: }
                   11371: 
1.28      www      11372: # --------------------------------------------------------- Value of a Variable
1.58      www      11373: sub EXT {
1.715     albertel 11374: 
1.1172.2.28  raeburn  11375:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11376:     unless ($varname) { return ''; }
1.218     albertel 11377:     #get real user name/domain, courseid and symb
                   11378:     my $courseid;
1.359     albertel 11379:     my $publicuser;
1.427     www      11380:     if ($symbparm) {
                   11381: 	$symbparm=&get_symb_from_alias($symbparm);
                   11382:     }
1.218     albertel 11383:     if (!($uname && $udom)) {
1.790     albertel 11384:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11385:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11386:     } else {
1.620     albertel 11387: 	$courseid=$env{'request.course.id'};
1.218     albertel 11388:     }
1.48      www      11389:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11390:     my $rest;
1.320     albertel 11391:     if (defined($therest[0])) {
1.48      www      11392:        $rest=join('.',@therest);
                   11393:     } else {
                   11394:        $rest='';
                   11395:     }
1.320     albertel 11396: 
1.57      www      11397:     my $qualifierrest=$qualifier;
                   11398:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11399:     my $spacequalifierrest=$space;
                   11400:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11401:     if ($realm eq 'user') {
1.48      www      11402: # --------------------------------------------------------------- user.resource
                   11403: 	if ($space eq 'resource') {
1.651     albertel 11404: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11405: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11406: 		 &&
1.744     albertel 11407: 		 ($symbparm eq &symbread()) ) {	
                   11408: 		# if we are in the middle of processing the resource the
                   11409: 		# get the value we are planning on committing
                   11410:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11411:                     return $Apache::lonhomework::results{$qualifierrest};
                   11412:                 } else {
                   11413:                     return $Apache::lonhomework::history{$qualifierrest};
                   11414:                 }
1.335     albertel 11415: 	    } else {
1.359     albertel 11416: 		my %restored;
1.620     albertel 11417: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11418: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11419: 		} else {
                   11420: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11421: 		}
1.335     albertel 11422: 		return $restored{$qualifierrest};
                   11423: 	    }
1.48      www      11424: # ----------------------------------------------------------------- user.access
                   11425:         } elsif ($space eq 'access') {
1.218     albertel 11426: 	    # FIXME - not supporting calls for a specific user
1.48      www      11427:             return &allowed($qualifier,$rest);
                   11428: # ------------------------------------------ user.preferences, user.environment
                   11429:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11430: 	    if (($uname eq $env{'user.name'}) &&
                   11431: 		($udom eq $env{'user.domain'})) {
                   11432: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11433: 	    } else {
1.359     albertel 11434: 		my %returnhash;
                   11435: 		if (!$publicuser) {
                   11436: 		    %returnhash=&userenvironment($udom,$uname,
                   11437: 						 $qualifierrest);
                   11438: 		}
1.218     albertel 11439: 		return $returnhash{$qualifierrest};
                   11440: 	    }
1.48      www      11441: # ----------------------------------------------------------------- user.course
                   11442:         } elsif ($space eq 'course') {
1.218     albertel 11443: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11444:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11445: # ------------------------------------------------------------------- user.role
                   11446:         } elsif ($space eq 'role') {
1.218     albertel 11447: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11448:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11449:             if ($qualifier eq 'value') {
                   11450: 		return $role;
                   11451:             } elsif ($qualifier eq 'extent') {
                   11452:                 return $where;
                   11453:             }
                   11454: # ----------------------------------------------------------------- user.domain
                   11455:         } elsif ($space eq 'domain') {
1.218     albertel 11456:             return $udom;
1.48      www      11457: # ------------------------------------------------------------------- user.name
                   11458:         } elsif ($space eq 'name') {
1.218     albertel 11459:             return $uname;
1.48      www      11460: # ---------------------------------------------------- Any other user namespace
1.29      www      11461:         } else {
1.359     albertel 11462: 	    my %reply;
                   11463: 	    if (!$publicuser) {
                   11464: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11465: 	    }
                   11466: 	    return $reply{$qualifierrest};
1.48      www      11467:         }
1.236     www      11468:     } elsif ($realm eq 'query') {
                   11469: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11470:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11471: 						[$spacequalifierrest]);
1.620     albertel 11472: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11473:    } elsif ($realm eq 'request') {
1.48      www      11474: # ------------------------------------------------------------- request.browser
                   11475:         if ($space eq 'browser') {
1.1145    bisitz   11476:             return $env{'browser.'.$qualifier};
1.57      www      11477: # ------------------------------------------------------------ request.filename
                   11478:         } else {
1.620     albertel 11479:             return $env{'request.'.$spacequalifierrest};
1.29      www      11480:         }
1.28      www      11481:     } elsif ($realm eq 'course') {
1.48      www      11482: # ---------------------------------------------------------- course.description
1.620     albertel 11483:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11484:     } elsif ($realm eq 'resource') {
1.165     www      11485: 
1.620     albertel 11486: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11487: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11488: 	}
1.693     albertel 11489: 
1.1172.2.30  raeburn  11490:         if ($qualifier eq '') {
                   11491: 	    if ($space eq 'title') {
                   11492: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11493: 	        return &gettitle($symbparm);
                   11494: 	    }
1.693     albertel 11495: 	
1.1172.2.30  raeburn  11496: 	    if ($space eq 'map') {
                   11497: 	        my ($map) = &decode_symb($symbparm);
                   11498: 	        return &symbread($map);
                   11499: 	    }
                   11500:             if ($space eq 'maptitle') {
                   11501:                 my ($map) = &decode_symb($symbparm);
                   11502:                 return &gettitle($map);
                   11503:             }
                   11504: 	    if ($space eq 'filename') {
                   11505: 	        if ($symbparm) {
                   11506: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11507: 	        }
                   11508: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11509: 	    }
1.1172.2.30  raeburn  11510: 
                   11511:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11512:                 if ($space eq 'visibleparts') {
                   11513:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11514:                     my $item;
                   11515:                     if (ref($navmap)) {
                   11516:                         my $res = $navmap->getBySymb($symbparm);
                   11517:                         my $parts = $res->parts();
                   11518:                         if (ref($parts) eq 'ARRAY') {
                   11519:                             $item = join(',',@{$parts});
                   11520:                         }
                   11521:                         undef($navmap);
                   11522:                     }
                   11523:                     return $item;
                   11524:                 }
                   11525:             }
                   11526:         }
1.693     albertel 11527: 
                   11528: 	my ($section, $group, @groups);
1.593     albertel 11529: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11530:         if (($courseid eq '') && ($cid)) {
                   11531:             $courseid = $cid;
                   11532:         }
                   11533: 	if (($symbparm && $courseid) && 
                   11534: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11535: 
1.218     albertel 11536: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11537: 
1.60      www      11538: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11539: 	    my $symbp=$symbparm;
1.735     albertel 11540: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11541: 
                   11542: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11543: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11544: 
1.620     albertel 11545: 	    if (($env{'user.name'} eq $uname) &&
                   11546: 		($env{'user.domain'} eq $udom)) {
                   11547: 		$section=$env{'request.course.sec'};
1.733     raeburn  11548:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11549:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11550: 	    } else {
1.539     albertel 11551: 		if (! defined($usection)) {
1.551     albertel 11552: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11553: 		} else {
                   11554: 		    $section = $usection;
                   11555: 		}
1.733     raeburn  11556:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11557: 	    }
                   11558: 
                   11559: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11560: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11561: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11562: 
1.593     albertel 11563: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11564: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11565: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11566: 
1.60      www      11567: # ----------------------------------------------------------- first, check user
1.624     albertel 11568: 
                   11569: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11570: 				       ([$courselevelr,'resource'],
                   11571: 					[$courselevelm,'map'     ],
                   11572: 					[$courselevel, 'course'  ]));
1.931     albertel 11573: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11574: 
1.594     albertel 11575: # ------------------------------------------------ second, check some of course
1.684     raeburn  11576:             my $coursereply;
1.691     raeburn  11577:             if (@groups > 0) {
                   11578:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11579:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11580:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11581:             }
1.96      www      11582: 
1.684     raeburn  11583: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11584: 				  $env{'course.'.$courseid.'.domain'},
                   11585: 				  'course',
                   11586: 				  ([$seclevelr,   'resource'],
                   11587: 				   [$seclevelm,   'map'     ],
                   11588: 				   [$seclevel,    'course'  ],
                   11589: 				   [$courselevelr,'resource']));
                   11590: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11591: 
1.60      www      11592: # ------------------------------------------------------ third, check map parms
1.218     albertel 11593: 	    my %parmhash=();
                   11594: 	    my $thisparm='';
                   11595: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11596: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11597: 		    &GDBM_READER(),0640)) {
1.218     albertel 11598: 		$thisparm=$parmhash{$symbparm};
                   11599: 		untie(%parmhash);
                   11600: 	    }
1.927     albertel 11601: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11602: 	}
1.594     albertel 11603: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11604: 
1.218     albertel 11605: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11606: 	my $filename;
                   11607: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11608: 	if ($symbparm) {
1.409     www      11609: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11610: 	} else {
1.620     albertel 11611: 	    $filename=$env{'request.filename'};
1.282     albertel 11612: 	}
                   11613: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11614: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11615: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11616: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11617: 
1.927     albertel 11618: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11619: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11620: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11621: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11622: 				     $env{'course.'.$courseid.'.domain'},
                   11623: 				     'course',
1.927     albertel 11624: 				     ([$courselevelm,'map'   ],
                   11625: 				      [$courselevel, 'course']));
                   11626: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11627: 	}
1.145     www      11628: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11629: 	unless ($space eq '0') {
1.336     albertel 11630: 	    my @parts=split(/_/,$space);
                   11631: 	    my $id=pop(@parts);
                   11632: 	    my $part=join('_',@parts);
                   11633: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11634: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11635: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11636: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11637: 	}
1.395     albertel 11638: 	if ($recurse) { return undef; }
                   11639: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11640: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11641: # ---------------------------------------------------- Any other user namespace
                   11642:     } elsif ($realm eq 'environment') {
                   11643: # ----------------------------------------------------------------- environment
1.620     albertel 11644: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11645: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11646: 	} else {
1.770     albertel 11647: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11648: 		return '';
                   11649: 	    }
1.219     albertel 11650: 	    my %returnhash=&userenvironment($udom,$uname,
                   11651: 					    $spacequalifierrest);
                   11652: 	    return $returnhash{$spacequalifierrest};
                   11653: 	}
1.28      www      11654:     } elsif ($realm eq 'system') {
1.48      www      11655: # ----------------------------------------------------------------- system.time
                   11656: 	if ($space eq 'time') {
                   11657: 	    return time;
                   11658:         }
1.696     albertel 11659:     } elsif ($realm eq 'server') {
                   11660: # ----------------------------------------------------------------- system.time
                   11661: 	if ($space eq 'name') {
                   11662: 	    return $ENV{'SERVER_NAME'};
                   11663:         }
1.28      www      11664:     }
1.48      www      11665:     return '';
1.61      www      11666: }
                   11667: 
1.927     albertel 11668: sub get_reply {
                   11669:     my ($reply_value) = @_;
1.940     raeburn  11670:     if (ref($reply_value) eq 'ARRAY') {
                   11671:         if (wantarray) {
                   11672: 	    return @$reply_value;
                   11673:         }
                   11674:         return $reply_value->[0];
                   11675:     } else {
                   11676:         return $reply_value;
1.927     albertel 11677:     }
                   11678: }
                   11679: 
1.691     raeburn  11680: sub check_group_parms {
                   11681:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11682:     my @groupitems = ();
                   11683:     my $resultitem;
1.927     albertel 11684:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11685:     foreach my $group (@{$groups}) {
                   11686:         foreach my $level (@levels) {
1.927     albertel 11687:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11688:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11689:         }
                   11690:     }
                   11691:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11692:                             $env{'course.'.$courseid.'.domain'},
                   11693:                                      'course',@groupitems);
                   11694:     return $coursereply;
                   11695: }
                   11696: 
                   11697: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11698:     my ($courseid,@groups) = @_;
                   11699:     @groups = sort(@groups);
1.691     raeburn  11700:     return @groups;
                   11701: }
                   11702: 
1.395     albertel 11703: sub packages_tab_default {
                   11704:     my ($uri,$varname)=@_;
                   11705:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11706: 
                   11707:     my (@extension,@specifics,$do_default);
                   11708:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11709: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11710: 	if ($pack_type eq 'default') {
                   11711: 	    $do_default=1;
                   11712: 	} elsif ($pack_type eq 'extension') {
                   11713: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11714: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11715: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11716: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11717: 	}
                   11718:     }
                   11719:     # first look for a package that matches the requested part id
                   11720:     foreach my $package (@specifics) {
                   11721: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11722: 	next if ($pack_part ne $part);
                   11723: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11724: 	    return $packagetab{"$pack_type&$name&default"};
                   11725: 	}
                   11726:     }
                   11727:     # look for any possible matching non extension_ package
                   11728:     foreach my $package (@specifics) {
                   11729: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11730: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11731: 	    return $packagetab{"$pack_type&$name&default"};
                   11732: 	}
1.585     albertel 11733: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11734: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11735: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11736: 	}
                   11737:     }
1.738     albertel 11738:     # look for any posible extension_ match
                   11739:     foreach my $package (@extension) {
                   11740: 	my ($package,$pack_type)=@{$package};
                   11741: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11742: 	    return $packagetab{"$pack_type&$name&default"};
                   11743: 	}
                   11744: 	if (defined($packagetab{$package."&$name&default"})) {
                   11745: 	    return $packagetab{$package."&$name&default"};
                   11746: 	}
                   11747:     }
                   11748:     # look for a global default setting
                   11749:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11750: 	return $packagetab{"default&$name&default"};
                   11751:     }
1.395     albertel 11752:     return undef;
                   11753: }
                   11754: 
1.334     albertel 11755: sub add_prefix_and_part {
                   11756:     my ($prefix,$part)=@_;
                   11757:     my $keyroot;
                   11758:     if (defined($prefix) && $prefix !~ /^__/) {
                   11759: 	# prefix that has a part already
                   11760: 	$keyroot=$prefix;
                   11761:     } elsif (defined($prefix)) {
                   11762: 	# prefix that is missing a part
                   11763: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11764:     } else {
                   11765: 	# no prefix at all
                   11766: 	if (defined($part)) { $keyroot='_'.$part; }
                   11767:     }
                   11768:     return $keyroot;
                   11769: }
                   11770: 
1.71      www      11771: # ---------------------------------------------------------------- Get metadata
                   11772: 
1.599     albertel 11773: my %metaentry;
1.1070    www      11774: my %importedpartids;
1.1172.2.99  raeburn  11775: my %importedrespids;
1.71      www      11776: sub metadata {
1.176     www      11777:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11778:     $uri=&declutter($uri);
1.288     albertel 11779:     # if it is a non metadata possible uri return quickly
1.529     albertel 11780:     if (($uri eq '') || 
                   11781: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11782: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11783:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11784: 	return undef;
                   11785:     }
1.1172.2.49  raeburn  11786:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11787: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11788: 	return undef;
1.288     albertel 11789:     }
1.73      www      11790:     my $filename=$uri;
                   11791:     $uri=~s/\.meta$//;
1.172     www      11792: #
                   11793: # Is the metadata already cached?
1.177     www      11794: # Look at timestamp of caching
1.172     www      11795: # Everything is cached by the main uri, libraries are never directly cached
                   11796: #
1.428     albertel 11797:     if (!defined($liburi)) {
1.599     albertel 11798: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11799: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11800:     }
                   11801:     {
1.1069    www      11802: # Imported parts would go here
1.1172.2.99  raeburn  11803:         my @origfiletagids=();
1.1069    www      11804:         my $importedparts=0;
1.1172.2.99  raeburn  11805: 
                   11806: # Imported responseids would go here
                   11807:         my $importedresponses=0;
1.172     www      11808: #
                   11809: # Is this a recursive call for a library?
                   11810: #
1.599     albertel 11811: #	if (! exists($metacache{$uri})) {
                   11812: #	    $metacache{$uri}={};
                   11813: #	}
1.924     albertel 11814: 	my $cachetime = 60*60;
1.171     www      11815:         if ($liburi) {
                   11816: 	    $liburi=&declutter($liburi);
                   11817:             $filename=$liburi;
1.401     bowersj2 11818:         } else {
1.599     albertel 11819: 	    &devalidate_cache_new('meta',$uri);
                   11820: 	    undef(%metaentry);
1.401     bowersj2 11821: 	}
1.140     www      11822:         my %metathesekeys=();
1.73      www      11823:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11824: 	my $metastring;
1.1140    www      11825: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11826: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11827: 	    $metastring = 
1.929     albertel 11828: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11829: 					  ('grade_target' => 'meta'));
                   11830: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11831: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11832:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11833: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11834: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11835: 	    $metastring=&getfile($file);
1.489     albertel 11836: 	}
1.208     albertel 11837:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11838:         my $token;
1.140     www      11839:         undef %metathesekeys;
1.71      www      11840:         while ($token=$parser->get_token) {
1.339     albertel 11841: 	    if ($token->[0] eq 'S') {
                   11842: 		if (defined($token->[2]->{'package'})) {
1.172     www      11843: #
                   11844: # This is a package - get package info
                   11845: #
1.339     albertel 11846: 		    my $package=$token->[2]->{'package'};
                   11847: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11848: 		    if (defined($token->[2]->{'id'})) { 
                   11849: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11850: 		    }
1.599     albertel 11851: 		    if ($metaentry{':packages'}) {
                   11852: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11853: 		    } else {
1.599     albertel 11854: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11855: 		    }
1.736     albertel 11856: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11857: 			my $part=$keyroot;
                   11858: 			$part=~s/^\_//;
1.736     albertel 11859: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11860: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11861: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11862: 			    # ignore package.tab specified default values
                   11863:                             # here &package_tab_default() will fetch those
                   11864: 			    if ($subp eq 'default') { next; }
1.736     albertel 11865: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11866: 			    my $unikey;
                   11867: 			    if ($pack =~ /_0$/) {
                   11868: 				$unikey='parameter_0_'.$name;
                   11869: 				$part=0;
                   11870: 			    } else {
                   11871: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11872: 			    }
1.339     albertel 11873: 			    if ($subp eq 'display') {
                   11874: 				$value.=' [Part: '.$part.']';
                   11875: 			    }
1.599     albertel 11876: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11877: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11878: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11879: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11880: 			    }
1.599     albertel 11881: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11882: 				$metaentry{':'.$unikey}=
                   11883: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11884: 			    }
1.339     albertel 11885: 			}
                   11886: 		    }
                   11887: 		} else {
1.172     www      11888: #
                   11889: # This is not a package - some other kind of start tag
1.339     albertel 11890: #
                   11891: 		    my $entry=$token->[1];
1.1068    www      11892: 		    my $unikey='';
1.175     www      11893: 
1.339     albertel 11894: 		    if ($entry eq 'import') {
1.175     www      11895: #
                   11896: # Importing a library here
1.339     albertel 11897: #
1.1067    www      11898:                         my $location=$parser->get_text('/import');
                   11899:                         my $dir=$filename;
                   11900:                         $dir=~s|[^/]*$||;
                   11901:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11902: 
                   11903:                         my $importid=$token->[2]->{'id'};
1.1068    www      11904:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11905: #
                   11906: # Check metadata for imported file to
                   11907: # see if it contained response items
                   11908: #
                   11909:                         my %currmetaentry = %metaentry;
                   11910:                         my $libresponseorder = &metadata($location,'responseorder');
                   11911:                         my $origfile;
                   11912:                         if ($libresponseorder ne '') {
                   11913:                             if ($#origfiletagids<0) {
                   11914:                                 undef(%importedrespids);
                   11915:                                 undef(%importedpartids);
                   11916:                             }
                   11917:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11918:                             if (@{$importedrespids{$importid}} > 0) {
                   11919:                                 $importedresponses = 1;
                   11920: # We need to get the original file and the imported file to get the response order correct
                   11921: # Load and inspect original file
                   11922:                                 if ($#origfiletagids<0) {
                   11923:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11924:                                     $origfile=&getfile($origfilelocation);
                   11925:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11926:                                 }
                   11927:                             }
                   11928:                         }
                   11929: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11930: # hash populated for imported library file
                   11931:                         %metaentry = %currmetaentry;
                   11932:                         undef(%currmetaentry);
1.1068    www      11933:                         if ($importmode eq 'problem') {
1.1069    www      11934: # Import as problem/response
1.1068    www      11935:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11936:                         } elsif ($importmode eq 'part') {
                   11937: # Import as part(s)
1.1069    www      11938:                            $importedparts=1;
                   11939: # We need to get the original file and the imported file to get the part order correct
                   11940: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11941: # Load and inspect original file if we didn't do that already
                   11942:                            if ($#origfiletagids<0) {
                   11943:                                undef(%importedrespids);
                   11944:                                undef(%importedpartids);
                   11945:                                if ($origfile eq '') {
                   11946:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11947:                                    $origfile=&getfile($origfilelocation);
                   11948:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11949:                                }
1.1070    www      11950:                            }
                   11951: 
1.1069    www      11952: # Load and inspect imported file
                   11953:                            my $impfile=&getfile($location);
                   11954:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11955:                            if ($#impfilepartids>=0) {
                   11956: # This problem had parts
1.1070    www      11957:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11958:                            } else {
                   11959: # Importing by turning a single problem into a problem part
                   11960: # It gets the import-tags ID as part-ID
                   11961:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11962:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11963:                            }
1.1068    www      11964:                         } else {
                   11965: # Normal import
                   11966:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11967:                            if (defined($token->[2]->{'id'})) {
                   11968:                               $unikey.='_'.$token->[2]->{'id'};
                   11969:                            }
1.1067    www      11970:                         }
                   11971: 
1.339     albertel 11972: 			if ($depthcount<20) {
1.736     albertel 11973: 			    my $metadata = 
                   11974: 				&metadata($uri,'keys', $location,$unikey,
                   11975: 					  $depthcount+1);
                   11976: 			    foreach my $meta (split(',',$metadata)) {
                   11977: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11978: 				$metathesekeys{$meta}=1;
1.339     albertel 11979: 			    }
1.1068    www      11980: 			
                   11981:                         }
1.1067    www      11982: 		    } else {
                   11983: #
                   11984: # Not importing, some other kind of non-package, non-library start tag
                   11985: # 
                   11986:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11987:                         if (defined($token->[2]->{'id'})) {
                   11988:                             $unikey.='_'.$token->[2]->{'id'};
                   11989:                         }
1.339     albertel 11990: 			if (defined($token->[2]->{'name'})) { 
                   11991: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11992: 			}
                   11993: 			$metathesekeys{$unikey}=1;
1.736     albertel 11994: 			foreach my $param (@{$token->[3]}) {
                   11995: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11996: 				$token->[2]->{$param};
1.339     albertel 11997: 			}
                   11998: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11999: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12000: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12001: 		 # only ws inside the tag, and not in default, so use default
                   12002: 		 # as value
1.599     albertel 12003: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12004: 			} elsif ( $internaltext =~ /\S/ ) {
                   12005: 		  # something interesting inside the tag
                   12006: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12007: 			} else {
1.908     albertel 12008: 		  # no interesting values, don't set a default
1.339     albertel 12009: 			}
1.172     www      12010: # end of not-a-package not-a-library import
1.339     albertel 12011: 		    }
1.172     www      12012: # end of not-a-package start tag
1.339     albertel 12013: 		}
1.172     www      12014: # the next is the end of "start tag"
1.339     albertel 12015: 	    }
                   12016: 	}
1.483     albertel 12017: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12018: 	$extension = lc($extension);
                   12019: 	if ($extension eq 'htm') { $extension='html'; }
                   12020: 
1.737     albertel 12021: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12022: 	    #no specific packages #how's our extension
                   12023: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12024: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12025: 					 \%metathesekeys);
                   12026: 	}
1.883     albertel 12027: 
                   12028: 	if (!exists($metaentry{':packages'})
                   12029: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12030: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12031: 		#no specific packages well let's get default then
                   12032: 		if ($key!~/^default&/) { next; }
1.488     albertel 12033: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12034: 					     \%metathesekeys);
                   12035: 	    }
                   12036: 	}
1.338     www      12037: # are there custom rights to evaluate
1.599     albertel 12038: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12039: 
1.338     www      12040:     #
                   12041:     # Importing a rights file here
1.339     albertel 12042:     #
                   12043: 	    unless ($depthcount) {
1.599     albertel 12044: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12045: 		my $dir=$filename;
                   12046: 		$dir=~s|[^/]*$||;
                   12047: 		$location=&filelocation($dir,$location);
1.736     albertel 12048: 		my $rights_metadata =
                   12049: 		    &metadata($uri,'keys',$location,'_rights',
                   12050: 			      $depthcount+1);
                   12051: 		foreach my $rights (split(',',$rights_metadata)) {
                   12052: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12053: 		    $metathesekeys{$rights}=1;
1.339     albertel 12054: 		}
                   12055: 	    }
                   12056: 	}
1.737     albertel 12057: 	# uniqifiy package listing
                   12058: 	my %seen;
                   12059: 	my @uniq_packages =
                   12060: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12061: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12062: 
1.1172.2.99  raeburn  12063:         if (($importedresponses) || ($importedparts)) {
                   12064:             if ($importedparts) {
1.1070    www      12065: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12066:                 $metaentry{':partorder'}='';
                   12067:                 $metathesekeys{'partorder'}=1;
                   12068:             }
                   12069:             if ($importedresponses) {
                   12070: # We had imported responses and need to rebuild responseorder
                   12071:                 $metaentry{':responseorder'}='';
                   12072:                 $metathesekeys{'responseorder'}=1;
                   12073:             }
                   12074:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12075:                 my $origid = $origfiletagids[$index+1];
                   12076:                 if ($origfiletagids[$index] eq 'part') {
                   12077: # Original part, part of the problem
                   12078:                     if ($importedparts) {
                   12079:                         $metaentry{':partorder'}.=','.$origid;
                   12080:                     }
                   12081:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12082:                     if ($importedparts) {
                   12083: # We have imported parts at this position
                   12084:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12085:                     }
                   12086:                     if ($importedresponses) {
                   12087: # We have imported responses at this position
                   12088:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12089:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12090:                         }
                   12091:                     }
                   12092:                 } else {
                   12093: # Original response item, part of the problem
                   12094:                     if ($importedresponses) {
                   12095:                         $metaentry{':responseorder'}.=','.$origid;
                   12096:                     }
                   12097:                 }
                   12098:             }
                   12099:             if ($importedparts) {
                   12100:                 $metaentry{':partorder'}=~s/^\,//;
                   12101:             }
                   12102:             if ($importedresponses) {
                   12103:                 $metaentry{':responseorder'}=~s/^\,//;
                   12104:             }
1.1070    www      12105:         }
                   12106: 
1.737     albertel 12107: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12108: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12109: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12110: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12111: # this is the end of "was not already recently cached
1.71      www      12112:     }
1.599     albertel 12113:     return $metaentry{':'.$what};
1.261     albertel 12114: }
                   12115: 
1.488     albertel 12116: sub metadata_create_package_def {
1.483     albertel 12117:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12118:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12119:     if ($subp eq 'default') { next; }
                   12120:     
1.599     albertel 12121:     if (defined($metaentry{':packages'})) {
                   12122: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12123:     } else {
1.599     albertel 12124: 	$metaentry{':packages'}=$package;
1.483     albertel 12125:     }
                   12126:     my $value=$packagetab{$key};
                   12127:     my $unikey;
                   12128:     $unikey='parameter_0_'.$name;
1.599     albertel 12129:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12130:     $$metathesekeys{$unikey}=1;
1.599     albertel 12131:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12132: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12133:     }
1.599     albertel 12134:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12135: 	$metaentry{':'.$unikey}=
                   12136: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12137:     }
                   12138: }
                   12139: 
1.261     albertel 12140: sub metadata_generate_part0 {
                   12141:     my ($metadata,$metacache,$uri) = @_;
                   12142:     my %allnames;
1.737     albertel 12143:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12144: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12145: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12146: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12147: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12148: 	    $allnames{$name}=$part;
                   12149: 	  }
                   12150: 	}
                   12151:     }
                   12152:     foreach my $name (keys(%allnames)) {
                   12153:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12154:       my $key=":parameter_0_$name";
1.261     albertel 12155:       $$metacache{"$key.part"}='0';
                   12156:       $$metacache{"$key.name"}=$name;
1.428     albertel 12157:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12158: 					   $allnames{$name}.'_'.$name.
                   12159: 					   '.type'};
1.428     albertel 12160:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12161: 			     '.display'};
1.644     www      12162:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12163:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12164:       $$metacache{"$key.display"}=$olddis;
                   12165:     }
1.71      www      12166: }
                   12167: 
1.764     albertel 12168: # ------------------------------------------------------ Devalidate title cache
                   12169: 
                   12170: sub devalidate_title_cache {
                   12171:     my ($url)=@_;
                   12172:     if (!$env{'request.course.id'}) { return; }
                   12173:     my $symb=&symbread($url);
                   12174:     if (!$symb) { return; }
                   12175:     my $key=$env{'request.course.id'}."\0".$symb;
                   12176:     &devalidate_cache_new('title',$key);
                   12177: }
                   12178: 
1.1014    droeschl 12179: # ------------------------------------------------- Get the title of a course
                   12180: 
                   12181: sub current_course_title {
                   12182:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12183: }
1.301     www      12184: # ------------------------------------------------- Get the title of a resource
                   12185: 
                   12186: sub gettitle {
                   12187:     my $urlsymb=shift;
                   12188:     my $symb=&symbread($urlsymb);
1.534     albertel 12189:     if ($symb) {
1.620     albertel 12190: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12191: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12192: 	if (defined($cached)) { 
                   12193: 	    return $result;
                   12194: 	}
1.534     albertel 12195: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12196: 	my $title='';
1.907     albertel 12197: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12198: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12199: 	} else {
                   12200: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12201: 		    &GDBM_READER(),0640)) {
                   12202: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12203: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12204: 		untie(%bighash);
                   12205: 	    }
1.534     albertel 12206: 	}
                   12207: 	$title=~s/\&colon\;/\:/gs;
                   12208: 	if ($title) {
1.1159    www      12209: # Remember both $symb and $title for dynamic metadata
                   12210:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12211:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12212: # Cache this title and then return it
1.599     albertel 12213: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12214: 	}
                   12215: 	$urlsymb=$url;
                   12216:     }
                   12217:     my $title=&metadata($urlsymb,'title');
                   12218:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12219:     return $title;
1.301     www      12220: }
1.613     albertel 12221: 
1.614     albertel 12222: sub get_slot {
                   12223:     my ($which,$cnum,$cdom)=@_;
                   12224:     if (!$cnum || !$cdom) {
1.790     albertel 12225: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12226: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12227: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12228:     }
1.703     albertel 12229:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12230:     my %slotinfo;
                   12231:     if (exists($remembered{$key})) {
                   12232: 	$slotinfo{$which} = $remembered{$key};
                   12233:     } else {
                   12234: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12235: 	&Apache::lonhomework::showhash(%slotinfo);
                   12236: 	my ($tmp)=keys(%slotinfo);
                   12237: 	if ($tmp=~/^error:/) { return (); }
                   12238: 	$remembered{$key} = $slotinfo{$which};
                   12239:     }
1.616     albertel 12240:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12241: 	return %{$slotinfo{$which}};
                   12242:     }
                   12243:     return $slotinfo{$which};
1.614     albertel 12244: }
1.1150    raeburn  12245: 
                   12246: sub get_reservable_slots {
                   12247:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12248:     my $now = time;
                   12249:     my $reservable_info;
                   12250:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12251:     if (exists($remembered{$key})) {
                   12252:         $reservable_info = $remembered{$key};
                   12253:     } else {
                   12254:         my %resv;
                   12255:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12256:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12257:         $reservable_info = \%resv;
                   12258:         $remembered{$key} = $reservable_info;
                   12259:     }
                   12260:     return $reservable_info;
                   12261: }
                   12262: 
                   12263: sub get_course_slots {
                   12264:     my ($cnum,$cdom) = @_;
                   12265:     my $hashid=$cnum.':'.$cdom;
                   12266:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12267:     if (defined($cached)) {
                   12268:         if (ref($result) eq 'HASH') {
                   12269:             return %{$result};
                   12270:         }
                   12271:     } else {
                   12272:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12273:         my ($tmp) = keys(%slots);
                   12274:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12275:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12276:             return %slots;
                   12277:         }
                   12278:     }
                   12279:     return;
                   12280: }
                   12281: 
                   12282: sub devalidate_slots_cache {
                   12283:     my ($cnum,$cdom)=@_;
                   12284:     my $hashid=$cnum.':'.$cdom;
                   12285:     &devalidate_cache_new('allslots',$hashid);
                   12286: }
                   12287: 
1.1172.2.8  raeburn  12288: sub get_coursechange {
                   12289:     my ($cdom,$cnum) = @_;
                   12290:     if ($cdom eq '' || $cnum eq '') {
                   12291:         return unless ($env{'request.course.id'});
                   12292:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12293:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12294:     }
                   12295:     my $hashid=$cdom.'_'.$cnum;
                   12296:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12297:     if ((defined($cached)) && ($change ne '')) {
                   12298:         return $change;
                   12299:     } else {
                   12300:         my %crshash;
                   12301:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12302:         if ($crshash{'internal.contentchange'} eq '') {
                   12303:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12304:             if ($change eq '') {
                   12305:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12306:                 $change = $crshash{'internal.created'};
                   12307:             }
                   12308:         } else {
                   12309:             $change = $crshash{'internal.contentchange'};
                   12310:         }
                   12311:         my $cachetime = 600;
                   12312:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12313:     }
                   12314:     return $change;
                   12315: }
                   12316: 
                   12317: sub devalidate_coursechange_cache {
                   12318:     my ($cnum,$cdom)=@_;
                   12319:     my $hashid=$cnum.':'.$cdom;
                   12320:     &devalidate_cache_new('crschange',$hashid);
                   12321: }
                   12322: 
1.31      www      12323: # ------------------------------------------------- Update symbolic store links
                   12324: 
                   12325: sub symblist {
                   12326:     my ($mapname,%newhash)=@_;
1.438     www      12327:     $mapname=&deversion(&declutter($mapname));
1.31      www      12328:     my %hash;
1.620     albertel 12329:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12330:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12331:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12332: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12333: 		next if ($url eq 'last_known'
                   12334: 			 && $env{'form.no_update_last_known'});
                   12335: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12336: 						    $newhash{$url}->[1],
                   12337: 						    $newhash{$url}->[0]);
1.191     harris41 12338:             }
1.31      www      12339:             if (untie(%hash)) {
                   12340: 		return 'ok';
                   12341:             }
                   12342:         }
                   12343:     }
                   12344:     return 'error';
1.212     www      12345: }
                   12346: 
                   12347: # --------------------------------------------------------------- Verify a symb
                   12348: 
                   12349: sub symbverify {
1.1172.2.11  raeburn  12350:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12351:     my $thisfn=$thisurl;
1.439     www      12352:     $thisfn=&declutter($thisfn);
1.215     www      12353: # direct jump to resource in page or to a sequence - will construct own symbs
                   12354:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12355: # check URL part
1.409     www      12356:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12357: 
1.431     www      12358:     unless ($url eq $thisfn) { return 0; }
1.213     www      12359: 
1.216     www      12360:     $symb=&symbclean($symb);
1.510     www      12361:     $thisurl=&deversion($thisurl);
1.439     www      12362:     $thisfn=&deversion($thisfn);
1.213     www      12363: 
                   12364:     my %bighash;
                   12365:     my $okay=0;
1.431     www      12366: 
1.620     albertel 12367:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12368:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12369:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12370:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12371:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12372:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12373:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12374:             }
                   12375:         }
                   12376:         my $ids;
1.1172.2.122  raeburn  12377:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12378:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12379:         } else {
                   12380:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12381:         }
1.1102    raeburn  12382:         unless ($ids) {
1.1172.2.13  raeburn  12383:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12384:             $ids=$bighash{$idkey};
1.216     www      12385:         }
                   12386:         if ($ids) {
                   12387: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12388:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12389:                 $symb =~ s/\?.+$//;
                   12390:             }
1.800     albertel 12391: 	    foreach my $id (split(/\,/,$ids)) {
                   12392: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12393:                if (
                   12394:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12395:    eq $symb) {
1.1172.2.11  raeburn  12396:                    if (ref($encstate)) {
                   12397:                        $$encstate = $bighash{'encrypted_'.$id};
                   12398:                    }
1.1172.2.13  raeburn  12399:                    if (($env{'request.role.adv'}) ||
                   12400:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12401:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12402:                        $okay=1;
                   12403:                        last;
                   12404:                    }
                   12405:                }
                   12406:            }
1.216     www      12407:         }
1.213     www      12408: 	untie(%bighash);
                   12409:     }
                   12410:     return $okay;
1.31      www      12411: }
                   12412: 
1.210     www      12413: # --------------------------------------------------------------- Clean-up symb
                   12414: 
                   12415: sub symbclean {
                   12416:     my $symb=shift;
1.568     albertel 12417:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12418: # remove version from map
                   12419:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12420: 
1.210     www      12421: # remove version from URL
                   12422:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12423: 
1.507     www      12424: # remove wrapper
                   12425: 
1.510     www      12426:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12427:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12428:     return $symb;
1.409     www      12429: }
                   12430: 
                   12431: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12432: 
                   12433: sub encode_symb {
                   12434:     my ($map,$resid,$url)=@_;
                   12435:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12436: }
1.409     www      12437: 
                   12438: sub decode_symb {
1.568     albertel 12439:     my $symb=shift;
                   12440:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12441:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12442:     return (&fixversion($map),$resid,&fixversion($url));
                   12443: }
                   12444: 
                   12445: sub fixversion {
                   12446:     my $fn=shift;
1.609     banghart 12447:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12448:     my %bighash;
                   12449:     my $uri=&clutter($fn);
1.620     albertel 12450:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12451: # is this cached?
1.599     albertel 12452:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12453:     if (defined($cached)) { return $result; }
                   12454: # unfortunately not cached, or expired
1.620     albertel 12455:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12456: 	    &GDBM_READER(),0640)) {
                   12457:  	if ($bighash{'version_'.$uri}) {
                   12458:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12459:  	    unless (($version eq 'mostrecent') || 
                   12460: 		    ($version==&getversion($uri))) {
1.440     www      12461:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12462:  	    }
                   12463:  	}
                   12464:  	untie %bighash;
1.413     www      12465:     }
1.599     albertel 12466:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12467: }
                   12468: 
                   12469: sub deversion {
                   12470:     my $url=shift;
                   12471:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12472:     return $url;
1.210     www      12473: }
                   12474: 
1.31      www      12475: # ------------------------------------------------------ Return symb list entry
                   12476: 
                   12477: sub symbread {
1.1172.2.126  raeburn  12478:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12479:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12480:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12481:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12482:         unless (ref($possibles) eq 'HASH') {
                   12483:             if ($ignorecachednull) {
                   12484:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12485:             } else {
                   12486:                 return $env{$cache_str};
                   12487:             }
1.1172.2.66  raeburn  12488:         }
                   12489:     }
1.242     www      12490: # no filename provided? try from environment
1.1172.2.54  raeburn  12491:     unless ($thisfn) {
1.620     albertel 12492:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  12493:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12494:         }
                   12495:         $thisfn=$env{'request.filename'};
1.44      www      12496:     }
1.569     albertel 12497:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12498: # is that filename actually a symb? Verify, clean, and return
                   12499:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12500: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  12501: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12502: 	}
1.242     www      12503:     }
1.44      www      12504:     $thisfn=declutter($thisfn);
1.31      www      12505:     my %hash;
1.37      www      12506:     my %bighash;
                   12507:     my $syval='';
1.620     albertel 12508:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12509:         my $targetfn = $thisfn;
1.609     banghart 12510:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12511:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12512:         }
1.687     albertel 12513: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12514: 	    $targetfn=$1;
                   12515: 	}
1.1172.2.128  raeburn  12516:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  12517:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12518:                           &GDBM_READER(),0640)) {
                   12519: 	        $syval=$hash{$targetfn};
                   12520:                 untie(%hash);
                   12521:             }
1.1172.2.128  raeburn  12522:             if ($syval && $checkforblock) {
                   12523:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  12524:                 if (@blockers) {
                   12525:                     $syval='';
                   12526:                 }
                   12527:             }
1.37      www      12528:         }
                   12529: # ---------------------------------------------------------- There was an entry
                   12530:         if ($syval) {
1.601     albertel 12531: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12532: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12533: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12534: 		    #return $env{$cache_str}='';
1.601     albertel 12535: 		#}    
                   12536: 		#$syval.=$1;
                   12537: 	    #}
1.37      www      12538:         } else {
                   12539: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12540:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12541:                             &GDBM_READER(),0640)) {
1.37      www      12542: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12543:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12544:               unless ($ids) { 
                   12545:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12546:               }
                   12547:               unless ($ids) {
                   12548: # alias?
                   12549: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12550:               }
1.37      www      12551:               if ($ids) {
                   12552: # ------------------------------------------------------------------- Has ID(s)
                   12553:                  my @possibilities=split(/\,/,$ids);
1.39      www      12554:                  if ($#possibilities==0) {
                   12555: # ----------------------------------------------- There is only one possibility
1.37      www      12556: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12557: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12558: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12559:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  12560:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12561:                              $possibles->{$syval} = 1;
                   12562:                          }
1.1172.2.66  raeburn  12563:                      }
                   12564:                      if ($checkforblock) {
1.1172.2.126  raeburn  12565:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  12566:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  12567:                              if (@blockers) {
                   12568:                                  $syval = '';
                   12569:                                  untie(%bighash);
                   12570:                                  return $env{$cache_str}='';
                   12571:                              }
1.1172.2.66  raeburn  12572:                          }
                   12573:                      }
                   12574:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12575: # ------------------------------------------ There is more than one possibility
                   12576:                      my $realpossible=0;
1.800     albertel 12577:                      foreach my $id (@possibilities) {
                   12578: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12579:                          my $canaccess;
                   12580:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12581:                              $canaccess = 1;
                   12582:                          } else {
                   12583:                              $canaccess = &allowed('bre',$file);
                   12584:                          }
                   12585:                          if ($canaccess) {
                   12586:          		     my ($mapid,$resid)=split(/\./,$id);
                   12587:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12588:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12589:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  12590:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  12591:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12592:                                  if ($checkforblock) {
1.1172.2.127  raeburn  12593:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  12594:                                      if (@blockers > 0) {
                   12595:                                          $syval = '';
                   12596:                                      } else {
1.1172.2.66  raeburn  12597:                                          $syval = $poss_syval;
                   12598:                                          $realpossible++;
                   12599:                                      }
                   12600:                                  } else {
                   12601:                                      $syval = $poss_syval;
                   12602:                                      $realpossible++;
                   12603:                                  }
1.1172.2.126  raeburn  12604:                                  if ($syval) {
                   12605:                                      if (ref($possibles) eq 'HASH') {
                   12606:                                          $possibles->{$syval} = 1;
                   12607:                                      }
                   12608:                                  }
1.1172.2.66  raeburn  12609:                              }
1.39      www      12610: 			 }
1.191     harris41 12611:                      }
1.39      www      12612: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12613:                  } else {
                   12614:                      $syval='';
1.37      www      12615:                  }
                   12616: 	      }
1.1172.2.66  raeburn  12617:               untie(%bighash);
1.481     raeburn  12618:            }
1.31      www      12619:         }
1.62      www      12620:         if ($syval) {
1.1172.2.128  raeburn  12621: 	    return $env{$cache_str}=$syval;
1.62      www      12622:         }
1.31      www      12623:     }
1.949     raeburn  12624:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12625:     return $env{$cache_str}='';
1.31      www      12626: }
                   12627: 
                   12628: # ---------------------------------------------------------- Return random seed
                   12629: 
1.32      www      12630: sub numval {
                   12631:     my $txt=shift;
                   12632:     $txt=~tr/A-J/0-9/;
                   12633:     $txt=~tr/a-j/0-9/;
                   12634:     $txt=~tr/K-T/0-9/;
                   12635:     $txt=~tr/k-t/0-9/;
                   12636:     $txt=~tr/U-Z/0-5/;
                   12637:     $txt=~tr/u-z/0-5/;
                   12638:     $txt=~s/\D//g;
1.564     albertel 12639:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12640:     return int($txt);
1.368     albertel 12641: }
                   12642: 
1.484     albertel 12643: sub numval2 {
                   12644:     my $txt=shift;
                   12645:     $txt=~tr/A-J/0-9/;
                   12646:     $txt=~tr/a-j/0-9/;
                   12647:     $txt=~tr/K-T/0-9/;
                   12648:     $txt=~tr/k-t/0-9/;
                   12649:     $txt=~tr/U-Z/0-5/;
                   12650:     $txt=~tr/u-z/0-5/;
                   12651:     $txt=~s/\D//g;
                   12652:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12653:     my $total;
                   12654:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12655:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12656:     return int($total);
                   12657: }
                   12658: 
1.575     albertel 12659: sub numval3 {
                   12660:     use integer;
                   12661:     my $txt=shift;
                   12662:     $txt=~tr/A-J/0-9/;
                   12663:     $txt=~tr/a-j/0-9/;
                   12664:     $txt=~tr/K-T/0-9/;
                   12665:     $txt=~tr/k-t/0-9/;
                   12666:     $txt=~tr/U-Z/0-5/;
                   12667:     $txt=~tr/u-z/0-5/;
                   12668:     $txt=~s/\D//g;
                   12669:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12670:     my $total;
                   12671:     foreach my $val (@txts) { $total+=$val; }
                   12672:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12673:     return $total;
                   12674: }
                   12675: 
1.675     albertel 12676: sub digest {
                   12677:     my ($data)=@_;
                   12678:     my $digest=&Digest::MD5::md5($data);
                   12679:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12680:     my ($e,$f);
                   12681:     {
                   12682:         use integer;
                   12683:         $e=($a+$b);
                   12684:         $f=($c+$d);
                   12685:         if ($_64bit) {
                   12686:             $e=(($e<<32)>>32);
                   12687:             $f=(($f<<32)>>32);
                   12688:         }
                   12689:     }
                   12690:     if (wantarray) {
                   12691: 	return ($e,$f);
                   12692:     } else {
                   12693: 	my $g;
                   12694: 	{
                   12695: 	    use integer;
                   12696: 	    $g=($e+$f);
                   12697: 	    if ($_64bit) {
                   12698: 		$g=(($g<<32)>>32);
                   12699: 	    }
                   12700: 	}
                   12701: 	return $g;
                   12702:     }
                   12703: }
                   12704: 
1.368     albertel 12705: sub latest_rnd_algorithm_id {
1.675     albertel 12706:     return '64bit5';
1.366     albertel 12707: }
1.32      www      12708: 
1.503     albertel 12709: sub get_rand_alg {
                   12710:     my ($courseid)=@_;
1.790     albertel 12711:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12712:     if ($courseid) {
1.620     albertel 12713: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12714:     }
                   12715:     return &latest_rnd_algorithm_id();
                   12716: }
                   12717: 
1.562     albertel 12718: sub validCODE {
                   12719:     my ($CODE)=@_;
                   12720:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12721:     return 0;
                   12722: }
                   12723: 
1.491     albertel 12724: sub getCODE {
1.620     albertel 12725:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12726:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12727: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12728: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12729: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12730:     }
                   12731:     return undef;
                   12732: }
1.1133    foxr     12733: #
                   12734: #  Determines the random seed for a specific context:
                   12735: #
                   12736: # parameters:
                   12737: #   symb      - in course context the symb for the seed.
                   12738: #   course_id - The course id of the form domain_coursenum.
                   12739: #   domain    - Domain for the user.
                   12740: #   course    - Course for the user.
                   12741: #   cenv      - environment of the course.
                   12742: #
                   12743: # NOTE:
                   12744: #   All parameters are picked out of the environment if missing
                   12745: #   or not defined.
                   12746: #   If a symb cannot be determined the current time is used instead.
                   12747: #
                   12748: #  For a given well defined symb, courside, domain, username,
                   12749: #  and course environment, the seed is reproducible.
                   12750: #
1.31      www      12751: sub rndseed {
1.1133    foxr     12752:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12753:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12754:     if (!defined($symb)) {
1.366     albertel 12755: 	unless ($symb=$wsymb) { return time; }
                   12756:     }
1.1146    foxr     12757:     if (!defined $courseid) { 
                   12758: 	$courseid=$wcourseid; 
                   12759:     }
                   12760:     if (!defined $domain) { $domain=$wdomain; }
                   12761:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12762: 
                   12763:     my $which;
                   12764:     if (defined($cenv->{'rndseed'})) {
                   12765: 	$which = $cenv->{'rndseed'};
                   12766:     } else {
                   12767: 	$which =&get_rand_alg($courseid);
                   12768:     }
1.491     albertel 12769:     if (defined(&getCODE())) {
1.675     albertel 12770: 	if ($which eq '64bit5') {
                   12771: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12772: 	} elsif ($which eq '64bit4') {
1.575     albertel 12773: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12774: 	} else {
                   12775: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12776: 	}
1.675     albertel 12777:     } elsif ($which eq '64bit5') {
                   12778: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12779:     } elsif ($which eq '64bit4') {
                   12780: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12781:     } elsif ($which eq '64bit3') {
                   12782: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12783:     } elsif ($which eq '64bit2') {
                   12784: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12785:     } elsif ($which eq '64bit') {
                   12786: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12787:     }
                   12788:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12789: }
                   12790: 
                   12791: sub rndseed_32bit {
                   12792:     my ($symb,$courseid,$domain,$username)=@_;
                   12793:     {
                   12794: 	use integer;
                   12795: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12796: 	my $symbseed=numval($symb) << 22;
                   12797: 	my $namechck=unpack("%32C*",$username) << 17;
                   12798: 	my $nameseed=numval($username) << 12;
                   12799: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12800: 	my $courseseed=unpack("%32C*",$courseid);
                   12801: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12802: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12803: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12804: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12805: 	return $num;
                   12806:     }
                   12807: }
                   12808: 
                   12809: sub rndseed_64bit {
                   12810:     my ($symb,$courseid,$domain,$username)=@_;
                   12811:     {
                   12812: 	use integer;
                   12813: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12814: 	my $symbseed=numval($symb) << 10;
                   12815: 	my $namechck=unpack("%32S*",$username);
                   12816: 	
                   12817: 	my $nameseed=numval($username) << 21;
                   12818: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12819: 	my $courseseed=unpack("%32S*",$courseid);
                   12820: 	
                   12821: 	my $num1=$symbchck+$symbseed+$namechck;
                   12822: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12823: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12824: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12825: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12826: 	return "$num1,$num2";
1.155     albertel 12827:     }
1.366     albertel 12828: }
                   12829: 
1.443     albertel 12830: sub rndseed_64bit2 {
                   12831:     my ($symb,$courseid,$domain,$username)=@_;
                   12832:     {
                   12833: 	use integer;
                   12834: 	# strings need to be an even # of cahracters long, it it is odd the
                   12835:         # last characters gets thrown away
                   12836: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12837: 	my $symbseed=numval($symb) << 10;
                   12838: 	my $namechck=unpack("%32S*",$username.' ');
                   12839: 	
                   12840: 	my $nameseed=numval($username) << 21;
1.501     albertel 12841: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12842: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12843: 	
                   12844: 	my $num1=$symbchck+$symbseed+$namechck;
                   12845: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12846: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12847: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12848: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12849: 	return "$num1,$num2";
                   12850:     }
                   12851: }
                   12852: 
                   12853: sub rndseed_64bit3 {
                   12854:     my ($symb,$courseid,$domain,$username)=@_;
                   12855:     {
                   12856: 	use integer;
                   12857: 	# strings need to be an even # of cahracters long, it it is odd the
                   12858:         # last characters gets thrown away
                   12859: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12860: 	my $symbseed=numval2($symb) << 10;
                   12861: 	my $namechck=unpack("%32S*",$username.' ');
                   12862: 	
                   12863: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12864: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12865: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12866: 	
                   12867: 	my $num1=$symbchck+$symbseed+$namechck;
                   12868: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12869: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12870: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12871: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12872: 	
1.503     albertel 12873: 	return "$num1:$num2";
1.443     albertel 12874:     }
                   12875: }
                   12876: 
1.575     albertel 12877: sub rndseed_64bit4 {
                   12878:     my ($symb,$courseid,$domain,$username)=@_;
                   12879:     {
                   12880: 	use integer;
                   12881: 	# strings need to be an even # of cahracters long, it it is odd the
                   12882:         # last characters gets thrown away
                   12883: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12884: 	my $symbseed=numval3($symb) << 10;
                   12885: 	my $namechck=unpack("%32S*",$username.' ');
                   12886: 	
                   12887: 	my $nameseed=numval3($username) << 21;
                   12888: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12889: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12890: 	
                   12891: 	my $num1=$symbchck+$symbseed+$namechck;
                   12892: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12893: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12894: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12895: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12896: 	
1.575     albertel 12897: 	return "$num1:$num2";
                   12898:     }
                   12899: }
                   12900: 
1.675     albertel 12901: sub rndseed_64bit5 {
                   12902:     my ($symb,$courseid,$domain,$username)=@_;
                   12903:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12904:     return "$num1:$num2";
                   12905: }
                   12906: 
1.366     albertel 12907: sub rndseed_CODE_64bit {
                   12908:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12909:     {
1.366     albertel 12910: 	use integer;
1.443     albertel 12911: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12912: 	my $symbseed=numval2($symb);
1.491     albertel 12913: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12914: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12915: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12916: 	my $num1=$symbseed+$CODEchck;
                   12917: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12918: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12919: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12920: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12921: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12922: 	return "$num1:$num2";
1.366     albertel 12923:     }
                   12924: }
                   12925: 
1.575     albertel 12926: sub rndseed_CODE_64bit4 {
                   12927:     my ($symb,$courseid,$domain,$username)=@_;
                   12928:     {
                   12929: 	use integer;
                   12930: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12931: 	my $symbseed=numval3($symb);
                   12932: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12933: 	my $CODEseed=numval3(&getCODE());
                   12934: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12935: 	my $num1=$symbseed+$CODEchck;
                   12936: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12937: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12938: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12939: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12940: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12941: 	return "$num1:$num2";
                   12942:     }
                   12943: }
                   12944: 
1.675     albertel 12945: sub rndseed_CODE_64bit5 {
                   12946:     my ($symb,$courseid,$domain,$username)=@_;
                   12947:     my $code = &getCODE();
                   12948:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12949:     return "$num1:$num2";
                   12950: }
                   12951: 
1.366     albertel 12952: sub setup_random_from_rndseed {
                   12953:     my ($rndseed)=@_;
1.503     albertel 12954:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12955: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12956:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12957:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12958:         } else {
                   12959:             &Math::Random::random_set_seed($num1,$num2);
                   12960:         }
1.366     albertel 12961:     } else {
                   12962: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12963:     }
1.36      albertel 12964: }
                   12965: 
1.474     albertel 12966: sub latest_receipt_algorithm_id {
1.835     albertel 12967:     return 'receipt3';
1.474     albertel 12968: }
                   12969: 
1.480     www      12970: sub recunique {
                   12971:     my $fucourseid=shift;
                   12972:     my $unique;
1.835     albertel 12973:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12974: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12975: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12976:     } else {
                   12977: 	$unique=$perlvar{'lonReceipt'};
                   12978:     }
                   12979:     return unpack("%32C*",$unique);
                   12980: }
                   12981: 
                   12982: sub recprefix {
                   12983:     my $fucourseid=shift;
                   12984:     my $prefix;
1.835     albertel 12985:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12986: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12987: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12988:     } else {
                   12989: 	$prefix=$perlvar{'lonHostID'};
                   12990:     }
                   12991:     return unpack("%32C*",$prefix);
                   12992: }
                   12993: 
1.76      www      12994: sub ireceipt {
1.474     albertel 12995:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12996: 
                   12997:     my $return =&recprefix($fucourseid).'-';
                   12998: 
                   12999:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13000: 	$env{'request.state'} eq 'construct') {
                   13001: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13002: 	return $return;
                   13003:     }
                   13004: 
1.76      www      13005:     my $cuname=unpack("%32C*",$funame);
                   13006:     my $cudom=unpack("%32C*",$fudom);
                   13007:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13008:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13009:     my $cunique=&recunique($fucourseid);
1.474     albertel 13010:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13011:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13012: 
1.790     albertel 13013: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13014: 			       
                   13015: 	$return.= ($cunique%$cuname+
                   13016: 		   $cunique%$cudom+
                   13017: 		   $cusymb%$cuname+
                   13018: 		   $cusymb%$cudom+
                   13019: 		   $cucourseid%$cuname+
                   13020: 		   $cucourseid%$cudom+
                   13021: 		   $cpart%$cuname+
                   13022: 		   $cpart%$cudom);
                   13023:     } else {
                   13024: 	$return.= ($cunique%$cuname+
                   13025: 		   $cunique%$cudom+
                   13026: 		   $cusymb%$cuname+
                   13027: 		   $cusymb%$cudom+
                   13028: 		   $cucourseid%$cuname+
                   13029: 		   $cucourseid%$cudom);
                   13030:     }
                   13031:     return $return;
1.76      www      13032: }
                   13033: 
                   13034: sub receipt {
1.474     albertel 13035:     my ($part)=@_;
1.790     albertel 13036:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13037:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13038: }
1.260     ng       13039: 
1.790     albertel 13040: sub whichuser {
                   13041:     my ($passedsymb)=@_;
                   13042:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13043:     if (defined($env{'form.grade_symb'})) {
                   13044: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13045: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13046: 	if (!$allowed &&
                   13047: 	    exists($env{'request.course.sec'}) &&
                   13048: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13049: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13050: 			      '/'.$env{'request.course.sec'});
                   13051: 	}
                   13052: 	if ($allowed) {
                   13053: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13054: 	    $courseid=$tmp_courseid;
                   13055: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13056: 	    ($name)=&get_env_multiple('form.grade_username');
                   13057: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13058: 	}
                   13059:     }
                   13060:     if (!$passedsymb) {
                   13061: 	$symb=&symbread();
                   13062:     } else {
                   13063: 	$symb=$passedsymb;
                   13064:     }
                   13065:     $courseid=$env{'request.course.id'};
                   13066:     $domain=$env{'user.domain'};
                   13067:     $name=$env{'user.name'};
                   13068:     if ($name eq 'public' && $domain eq 'public') {
                   13069: 	if (!defined($env{'form.username'})) {
                   13070: 	    $env{'form.username'}.=time.rand(10000000);
                   13071: 	}
                   13072: 	$name.=$env{'form.username'};
                   13073:     }
                   13074:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13075: 
                   13076: }
                   13077: 
1.36      albertel 13078: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13079: # returns either the contents of the file or 
                   13080: # -1 if the file doesn't exist
1.481     raeburn  13081: #
                   13082: # if the target is a file that was uploaded via DOCS, 
                   13083: # a check will be made to see if a current copy exists on the local server,
                   13084: # if it does this will be served, otherwise a copy will be retrieved from
                   13085: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13086: # the local server.   
1.472     albertel 13087: 
1.36      albertel 13088: sub getfile {
1.538     albertel 13089:     my ($file) = @_;
1.609     banghart 13090:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13091:     &repcopy($file);
                   13092:     return &readfile($file);
                   13093: }
                   13094: 
                   13095: sub repcopy_userfile {
                   13096:     my ($file)=@_;
1.1142    raeburn  13097:     my $londocroot = $perlvar{'lonDocRoot'};
                   13098:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13099:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13100:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13101: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13102:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13103:     if (-e "$file") {
1.828     www      13104: # we already have a local copy, check it out
1.538     albertel 13105: 	my @fileinfo = stat($file);
1.828     www      13106: 	my $rtncode;
                   13107: 	my $info;
1.538     albertel 13108: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13109: 	if ($lwpresp ne 'ok') {
1.828     www      13110: # there is no such file anymore, even though we had a local copy
1.482     albertel 13111: 	    if ($rtncode eq '404') {
1.538     albertel 13112: 		unlink($file);
1.482     albertel 13113: 	    }
                   13114: 	    return -1;
                   13115: 	}
                   13116: 	if ($info < $fileinfo[9]) {
1.828     www      13117: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13118: 	    return 'ok';
1.828     www      13119: 	} else {
                   13120: # the file is outdated, get rid of it
                   13121: 	    unlink($file);
1.482     albertel 13122: 	}
1.828     www      13123:     }
                   13124: # one way or the other, at this point, we don't have the file
                   13125: # construct the correct path for the file
                   13126:     my @parts = ($cdom,$cnum); 
                   13127:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13128: 	push @parts, split(/\//,$1);
                   13129:     }
                   13130:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13131:     foreach my $part (@parts) {
                   13132: 	$path .= '/'.$part;
                   13133: 	if (!-e $path) {
                   13134: 	    mkdir($path,0770);
1.482     albertel 13135: 	}
                   13136:     }
1.828     www      13137: # now the path exists for sure
                   13138: # get a user agent
                   13139:     my $ua=new LWP::UserAgent;
                   13140:     my $transferfile=$file.'.in.transfer';
                   13141: # FIXME: this should flock
                   13142:     if (-e $transferfile) { return 'ok'; }
                   13143:     my $request;
                   13144:     $uri=~s/^\///;
1.980     raeburn  13145:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13146:     my $hostname = &hostname($homeserver);
1.980     raeburn  13147:     my $protocol = $protocol{$homeserver};
                   13148:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13149:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13150:     my $response=$ua->request($request,$transferfile);
                   13151: # did it work?
                   13152:     if ($response->is_error()) {
                   13153: 	unlink($transferfile);
                   13154: 	&logthis("Userfile repcopy failed for $uri");
                   13155: 	return -1;
                   13156:     }
                   13157: # worked, rename the transfer file
                   13158:     rename($transferfile,$file);
1.607     raeburn  13159:     return 'ok';
1.481     raeburn  13160: }
                   13161: 
1.517     albertel 13162: sub tokenwrapper {
                   13163:     my $uri=shift;
1.980     raeburn  13164:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13165:     $uri=~s|^/||;
1.620     albertel 13166:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13167:     my $token=$1;
1.552     albertel 13168:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13169:     if ($udom && $uname && $file) {
                   13170: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13171:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13172:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13173:         my $hostname = &hostname($homeserver);
1.980     raeburn  13174:         my $protocol = $protocol{$homeserver};
                   13175:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13176:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13177:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13178:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13179:     } else {
                   13180:         return '/adm/notfound.html';
                   13181:     }
                   13182: }
                   13183: 
1.828     www      13184: # call with reqtype HEAD: get last modification time
                   13185: # call with reqtype GET: get the file contents
                   13186: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13187: #
1.481     raeburn  13188: sub getuploaded {
                   13189:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13190:     $uri=~s/^\///;
1.980     raeburn  13191:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13192:     my $hostname = &hostname($homeserver);
1.980     raeburn  13193:     my $protocol = $protocol{$homeserver};
                   13194:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13195:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13196:     my $ua=new LWP::UserAgent;
                   13197:     my $request=new HTTP::Request($reqtype,$uri);
                   13198:     my $response=$ua->request($request);
                   13199:     $$rtncode = $response->code;
1.482     albertel 13200:     if (! $response->is_success()) {
                   13201: 	return 'failed';
                   13202:     }      
                   13203:     if ($reqtype eq 'HEAD') {
1.486     www      13204: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13205:     } elsif ($reqtype eq 'GET') {
                   13206: 	$$info = $response->content;
1.472     albertel 13207:     }
1.482     albertel 13208:     return 'ok';
1.36      albertel 13209: }
                   13210: 
1.481     raeburn  13211: sub readfile {
                   13212:     my $file = shift;
                   13213:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13214:     my $fh;
1.1172.2.96  raeburn  13215:     open($fh,"<",$file);
1.481     raeburn  13216:     my $a='';
1.800     albertel 13217:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13218:     return $a;
                   13219: }
                   13220: 
1.36      albertel 13221: sub filelocation {
1.590     banghart 13222:     my ($dir,$file) = @_;
                   13223:     my $location;
                   13224:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13225: 
                   13226:     if ($file =~ m-^/adm/-) {
                   13227: 	$file=~s-^/adm/wrapper/-/-;
                   13228: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13229:     }
1.882     albertel 13230: 
1.1139    www      13231:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13232:         $location = $file;
1.609     banghart 13233:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13234:         my ($udom,$uname,$filename)=
1.811     albertel 13235:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13236:         my $home=&homeserver($uname,$udom);
                   13237:         my $is_me=0;
                   13238:         my @ids=&current_machine_ids();
                   13239:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13240:         if ($is_me) {
1.1117    foxr     13241:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13242:         } else {
                   13243:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13244:   	      $udom.'/'.$uname.'/'.$filename;
                   13245:         }
1.882     albertel 13246:     } elsif ($file =~ m-^/adm/-) {
                   13247: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13248:     } else {
                   13249:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13250:         $file=~s:^/(res|priv)/:/:;
                   13251:         my $space=$1;
1.590     banghart 13252:         if ( !( $file =~ m:^/:) ) {
                   13253:             $location = $dir. '/'.$file;
                   13254:         } else {
1.1142    raeburn  13255:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13256:         }
1.59      albertel 13257:     }
1.590     banghart 13258:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13259:     while ($location=~m{/\.\./}) {
                   13260: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13261: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13262: 	} else {
                   13263: 	    $location=~ s{/\.\./}{/}g;
                   13264: 	}
                   13265:     } #remove dir/..
1.590     banghart 13266:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13267:     return $location;
1.46      www      13268: }
1.36      albertel 13269: 
1.46      www      13270: sub hreflocation {
                   13271:     my ($dir,$file)=@_;
1.980     raeburn  13272:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13273: 	$file=filelocation($dir,$file);
1.700     albertel 13274:     } elsif ($file=~m-^/adm/-) {
                   13275: 	$file=~s-^/adm/wrapper/-/-;
                   13276: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13277:     }
                   13278:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13279: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13280:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13281: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13282: 	        {/uploaded/$1/$2/}x;
1.46      www      13283:     }
1.913     albertel 13284:     if ($file=~ m{^/userfiles/}) {
                   13285: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13286:     }
1.462     albertel 13287:     return $file;
1.465     albertel 13288: }
                   13289: 
1.1139    www      13290: 
                   13291: 
                   13292: 
                   13293: 
1.465     albertel 13294: sub current_machine_domains {
1.853     albertel 13295:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13296: }
                   13297: 
                   13298: sub machine_domains {
                   13299:     my ($hostname) = @_;
1.465     albertel 13300:     my @domains;
1.838     albertel 13301:     my %hostname = &all_hostnames();
1.465     albertel 13302:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13303: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13304: 	if ($hostname eq $name) {
1.844     albertel 13305: 	    push(@domains,&host_domain($id));
1.465     albertel 13306: 	}
                   13307:     }
                   13308:     return @domains;
                   13309: }
                   13310: 
                   13311: sub current_machine_ids {
1.853     albertel 13312:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13313: }
                   13314: 
                   13315: sub machine_ids {
                   13316:     my ($hostname) = @_;
                   13317:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13318:     my @ids;
1.888     albertel 13319:     my %name_to_host = &all_names();
1.889     albertel 13320:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13321: 	return @{ $name_to_host{$hostname} };
                   13322:     }
                   13323:     return;
1.31      www      13324: }
                   13325: 
1.824     raeburn  13326: sub additional_machine_domains {
                   13327:     my @domains;
1.1172.2.96  raeburn  13328:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13329:     while( my $line = <$fh>) {
                   13330:         $line =~ s/\s//g;
                   13331:         push(@domains,$line);
                   13332:     }
                   13333:     return @domains;
                   13334: }
                   13335: 
                   13336: sub default_login_domain {
                   13337:     my $domain = $perlvar{'lonDefDomain'};
                   13338:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13339:     foreach my $posdom (&current_machine_domains(),
                   13340:                         &additional_machine_domains()) {
                   13341:         if (lc($posdom) eq lc($testdomain)) {
                   13342:             $domain=$posdom;
                   13343:             last;
                   13344:         }
                   13345:     }
                   13346:     return $domain;
                   13347: }
                   13348: 
1.1172.2.106  raeburn  13349: sub shared_institution {
                   13350:     my ($dom) = @_;
                   13351:     my $same_intdom;
                   13352:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13353:     if ($hostintdom ne '') {
                   13354:         my %iphost = &get_iphost();
                   13355:         my $primary_id = &domain($dom,'primary');
                   13356:         my $primary_ip = &get_host_ip($primary_id);
                   13357:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13358:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13359:                 my $intdom = &internet_dom($id);
                   13360:                 if ($intdom eq $hostintdom) {
                   13361:                     $same_intdom = 1;
                   13362:                     last;
                   13363:                 }
                   13364:             }
                   13365:         }
                   13366:     }
                   13367:     return $same_intdom;
                   13368: }
                   13369: 
1.1172.2.120  raeburn  13370: sub uses_sts {
                   13371:     my ($ignore_cache) = @_;
                   13372:     my $lonhost = $perlvar{'lonHostID'};
                   13373:     my $hostname = &hostname($lonhost);
                   13374:     my $sts_on;
                   13375:     if ($protocol{$lonhost} eq 'https') {
                   13376:         my $cachetime = 12*3600;
                   13377:         if (!$ignore_cache) {
                   13378:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13379:             if (defined($cached)) {
                   13380:                 return $sts_on;
                   13381:             }
                   13382:         }
1.1172.2.121  raeburn  13383:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13384:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13385:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13386:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13387:         if ($response->is_success) {
                   13388:             my $has_sts = $response->header('Strict-Transport-Security');
                   13389:             if ($has_sts eq '') {
                   13390:                 $sts_on = 0;
                   13391:             } else {
                   13392:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13393:                     my $maxage = $1;
                   13394:                     if ($maxage) {
                   13395:                         $sts_on = 1;
                   13396:                     } else {
                   13397:                         $sts_on = 0;
                   13398:                     }
                   13399:                 } else {
                   13400:                     $sts_on = 0;
                   13401:                 }
                   13402:             }
                   13403:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13404:         }
                   13405:     }
                   13406:     return;
                   13407: }
                   13408: 
1.1172.2.134  raeburn  13409: sub get_requestor_ip {
                   13410:     my ($r,$nolookup,$noproxy) = @_;
                   13411:     my $from_ip;
                   13412:     if (ref($r)) {
                   13413:         $from_ip = $r->get_remote_host($nolookup);
                   13414:     } else {
                   13415:         $from_ip = $ENV{'REMOTE_ADDR'};
                   13416:     }
                   13417:     return $from_ip;
                   13418: }
                   13419: 
1.31      www      13420: # ------------------------------------------------------------- Declutters URLs
                   13421: 
                   13422: sub declutter {
                   13423:     my $thisfn=shift;
1.569     albertel 13424:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13425:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13426:         $thisfn=~s{^/home/httpd/html}{};
                   13427:     }
1.31      www      13428:     $thisfn=~s/^\///;
1.697     albertel 13429:     $thisfn=~s|^adm/wrapper/||;
                   13430:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13431:     $thisfn=~s/^res\///;
1.1172    bisitz   13432:     $thisfn=~s/^priv\///;
1.1032    raeburn  13433:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13434:         $thisfn=~s/\?.+$//;
                   13435:     }
1.268     www      13436:     return $thisfn;
                   13437: }
                   13438: 
                   13439: # ------------------------------------------------------------- Clutter up URLs
                   13440: 
                   13441: sub clutter {
                   13442:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13443:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13444: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13445:        $thisfn='/res'.$thisfn; 
                   13446:     }
1.1031    raeburn  13447:     if ($thisfn !~m|^/adm|) {
                   13448: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13449: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13450: 	} else {
                   13451: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13452: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13453: 	    if ($embstyle eq 'ssi'
                   13454: 		|| ($embstyle eq 'hdn')
                   13455: 		|| ($embstyle eq 'rat')
                   13456: 		|| ($embstyle eq 'prv')
                   13457: 		|| ($embstyle eq 'ign')) {
                   13458: 		#do nothing with these
                   13459: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13460: 		|| ($embstyle eq 'emb')
                   13461: 		|| ($embstyle eq 'wrp')) {
                   13462: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13463: 	    } elsif ($embstyle eq 'unk'
                   13464: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13465: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13466: 	    } else {
1.718     www      13467: #		&logthis("Got a blank emb style");
1.695     albertel 13468: 	    }
1.694     albertel 13469: 	}
                   13470:     }
1.31      www      13471:     return $thisfn;
1.12      www      13472: }
                   13473: 
1.787     albertel 13474: sub clutter_with_no_wrapper {
                   13475:     my $uri = &clutter(shift);
                   13476:     if ($uri =~ m-^/adm/-) {
                   13477: 	$uri =~ s-^/adm/wrapper/-/-;
                   13478: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13479:     }
                   13480:     return $uri;
                   13481: }
                   13482: 
1.557     albertel 13483: sub freeze_escape {
                   13484:     my ($value)=@_;
                   13485:     if (ref($value)) {
                   13486: 	$value=&nfreeze($value);
                   13487: 	return '__FROZEN__'.&escape($value);
                   13488:     }
                   13489:     return &escape($value);
                   13490: }
                   13491: 
1.11      www      13492: 
1.557     albertel 13493: sub thaw_unescape {
                   13494:     my ($value)=@_;
                   13495:     if ($value =~ /^__FROZEN__/) {
                   13496: 	substr($value,0,10,undef);
                   13497: 	$value=&unescape($value);
                   13498: 	return &thaw($value);
                   13499:     }
                   13500:     return &unescape($value);
                   13501: }
                   13502: 
1.436     albertel 13503: sub correct_line_ends {
                   13504:     my ($result)=@_;
                   13505:     $$result =~s/\r\n/\n/mg;
                   13506:     $$result =~s/\r/\n/mg;
1.415     albertel 13507: }
1.1       albertel 13508: # ================================================================ Main Program
                   13509: 
1.184     www      13510: sub goodbye {
1.204     albertel 13511:    &logthis("Starting Shut down");
1.443     albertel 13512: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13513:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13514: #converted
1.599     albertel 13515: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13516:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13517: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13518: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13519: #1.1 only
1.870     albertel 13520: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13521: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13522: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13523: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13524:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13525:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13526:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13527:    &flushcourselogs();
                   13528:    &logthis("Shutting down");
                   13529: }
                   13530: 
1.852     albertel 13531: sub get_dns {
1.1172.2.17  raeburn  13532:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13533:     if (!$ignore_cache) {
                   13534: 	my ($content,$cached)=
                   13535: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13536: 	if ($cached) {
1.1172.2.17  raeburn  13537: 	    &$func($content,$hashref);
1.869     albertel 13538: 	    return;
                   13539: 	}
                   13540:     }
                   13541: 
                   13542:     my %alldns;
1.1172.2.96  raeburn  13543:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13544:         foreach my $dns (<$config>) {
                   13545: 	    next if ($dns !~ /^\^(\S*)/x);
                   13546:             my $line = $1;
                   13547:             my ($host,$protocol) = split(/:/,$line);
                   13548:             if ($protocol ne 'https') {
                   13549:                 $protocol = 'http';
                   13550:             }
                   13551: 	    $alldns{$host} = $protocol;
1.979     raeburn  13552:         }
1.1172.2.96  raeburn  13553:         close($config);
1.869     albertel 13554:     }
                   13555:     while (%alldns) {
1.1172.2.52  raeburn  13556: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13557: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13558:         $ua->timeout(30);
1.979     raeburn  13559: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13560: 	my $response=$ua->request($request);
1.979     raeburn  13561:         delete($alldns{$dns});
1.852     albertel 13562: 	next if ($response->is_error());
                   13563: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13564:         unless ($nocache) {
1.1172.2.23  raeburn  13565: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13566:         }
                   13567: 	&$func(\@content,$hashref);
1.869     albertel 13568: 	return;
1.852     albertel 13569:     }
1.871     albertel 13570:     my $which = (split('/',$url))[3];
                   13571:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13572:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13573:         my @content = <$config>;
                   13574:         &$func(\@content,$hashref);
                   13575:     }
1.1172.2.17  raeburn  13576:     return;
                   13577: }
                   13578: 
                   13579: # ------------------------------------------------------Get DNS checksums file
                   13580: sub parse_dns_checksums_tab {
                   13581:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13582:     my $lonhost = $perlvar{'lonHostID'};
                   13583:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13584:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13585:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13586:     my $webconfdir = '/etc/httpd/conf';
                   13587:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13588:         $webconfdir = '/etc/apache2';
                   13589:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13590:         if ($1 >= 10) {
                   13591:             $webconfdir = '/etc/apache2';
                   13592:         }
                   13593:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13594:         if ($1 >= 10.0) {
                   13595:             $webconfdir = '/etc/apache2';
                   13596:         }
                   13597:     }
1.1172.2.17  raeburn  13598:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13599:     my (%chksum,%revnum);
                   13600:     if (ref($lines) eq 'ARRAY') {
                   13601:         chomp(@{$lines});
1.1172.2.34  raeburn  13602:         my $version = shift(@{$lines});
                   13603:         if ($version eq $release) {
1.1172.2.17  raeburn  13604:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13605:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13606:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13607:                     if ($webconfdir eq '/etc/apache2') {
                   13608:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13609:                     }
                   13610:                 }
1.1172.2.34  raeburn  13611:                 $chksum{$file} = $shasum;
                   13612:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13613:             }
                   13614:             if (ref($hashref) eq 'HASH') {
                   13615:                 %{$hashref} = (
                   13616:                                 sums     => \%chksum,
                   13617:                                 versions => \%revnum,
                   13618:                               );
                   13619:             }
                   13620:         }
                   13621:     }
1.869     albertel 13622:     return;
1.852     albertel 13623: }
1.1172.2.17  raeburn  13624: 
                   13625: sub fetch_dns_checksums {
                   13626:     my %checksums;
1.1172.2.34  raeburn  13627:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13628:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13629:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13630:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13631:              \%checksums);
                   13632:     return \%checksums;
                   13633: }
                   13634: 
1.327     albertel 13635: # ------------------------------------------------------------ Read domain file
                   13636: {
1.852     albertel 13637:     my $loaded;
1.846     albertel 13638:     my %domain;
                   13639: 
1.852     albertel 13640:     sub parse_domain_tab {
                   13641: 	my ($lines) = @_;
                   13642: 	foreach my $line (@$lines) {
                   13643: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13644: 
1.846     albertel 13645: 	    chomp($line);
1.852     albertel 13646: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13647: 	    my %this_domain;
                   13648: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13649: 			       'lang_def', 'city', 'longi', 'lati',
                   13650: 			       'primary') {
                   13651: 		$this_domain{$field} = shift(@elements);
                   13652: 	    }
                   13653: 	    $domain{$name} = \%this_domain;
1.852     albertel 13654: 	}
                   13655:     }
1.864     albertel 13656: 
                   13657:     sub reset_domain_info {
                   13658: 	undef($loaded);
                   13659: 	undef(%domain);
                   13660:     }
                   13661: 
1.852     albertel 13662:     sub load_domain_tab {
1.1172.2.70  raeburn  13663: 	my ($ignore_cache,$nocache) = @_;
                   13664: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13665: 	my $fh;
1.1172.2.96  raeburn  13666: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13667: 	    my @lines = <$fh>;
                   13668: 	    &parse_domain_tab(\@lines);
1.448     albertel 13669: 	}
1.852     albertel 13670: 	close($fh);
                   13671: 	$loaded = 1;
1.327     albertel 13672:     }
1.846     albertel 13673: 
                   13674:     sub domain {
1.852     albertel 13675: 	&load_domain_tab() if (!$loaded);
                   13676: 
1.846     albertel 13677: 	my ($name,$what) = @_;
                   13678: 	return if ( !exists($domain{$name}) );
                   13679: 
                   13680: 	if (!$what) {
                   13681: 	    return $domain{$name}{'description'};
                   13682: 	}
                   13683: 	return $domain{$name}{$what};
                   13684:     }
1.974     raeburn  13685: 
                   13686:     sub domain_info {
                   13687:         &load_domain_tab() if (!$loaded);
                   13688:         return %domain;
                   13689:     }
                   13690: 
1.327     albertel 13691: }
                   13692: 
                   13693: 
1.1       albertel 13694: # ------------------------------------------------------------- Read hosts file
                   13695: {
1.838     albertel 13696:     my %hostname;
1.844     albertel 13697:     my %hostdom;
1.845     albertel 13698:     my %libserv;
1.852     albertel 13699:     my $loaded;
1.888     albertel 13700:     my %name_to_host;
1.1074    raeburn  13701:     my %internetdom;
1.1107    raeburn  13702:     my %LC_dns_serv;
1.852     albertel 13703: 
                   13704:     sub parse_hosts_tab {
                   13705: 	my ($file) = @_;
                   13706: 	foreach my $configline (@$file) {
                   13707: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13708:             chomp($configline);
                   13709: 	    if ($configline =~ /^\^/) {
                   13710:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13711:                     $LC_dns_serv{$1} = 1;
                   13712:                 }
                   13713:                 next;
                   13714:             }
1.1074    raeburn  13715: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13716: 	    $name=~s/\s//g;
                   13717: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13718:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13719:                     my $curr = $hostname{$id};
                   13720:                     my $skip;
                   13721:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13722:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13723:                             $skip = 1;
                   13724:                         } else {
                   13725:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13726:                         }
                   13727:                     }
                   13728:                     unless ($skip) {
                   13729:                         push(@{$name_to_host{$name}},$id);
                   13730:                     }
                   13731:                 } else {
                   13732:                     push(@{$name_to_host{$name}},$id);
                   13733:                 }
1.852     albertel 13734: 		$hostname{$id}=$name;
                   13735: 		$hostdom{$id}=$domain;
                   13736: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13737:                 if (defined($protocol)) {
                   13738:                     if ($protocol eq 'https') {
                   13739:                         $protocol{$id} = $protocol;
                   13740:                     } else {
                   13741:                         $protocol{$id} = 'http'; 
                   13742:                     }
1.968     raeburn  13743:                 } else {
1.969     raeburn  13744:                     $protocol{$id} = 'http';
1.968     raeburn  13745:                 }
1.1074    raeburn  13746:                 if (defined($intdom)) {
                   13747:                     $internetdom{$id} = $intdom;
                   13748:                 }
1.852     albertel 13749: 	    }
                   13750: 	}
                   13751:     }
1.864     albertel 13752:     
                   13753:     sub reset_hosts_info {
1.897     albertel 13754: 	&purge_remembered();
1.864     albertel 13755: 	&reset_domain_info();
                   13756: 	&reset_hosts_ip_info();
1.892     albertel 13757: 	undef(%name_to_host);
1.864     albertel 13758: 	undef(%hostname);
                   13759: 	undef(%hostdom);
                   13760: 	undef(%libserv);
                   13761: 	undef($loaded);
                   13762:     }
1.1       albertel 13763: 
1.852     albertel 13764:     sub load_hosts_tab {
1.1172.2.70  raeburn  13765: 	my ($ignore_cache,$nocache) = @_;
                   13766: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13767: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13768: 	my @config = <$config>;
                   13769: 	&parse_hosts_tab(\@config);
                   13770: 	close($config);
                   13771: 	$loaded=1;
1.1       albertel 13772:     }
1.852     albertel 13773: 
1.838     albertel 13774:     sub hostname {
1.852     albertel 13775: 	&load_hosts_tab() if (!$loaded);
                   13776: 
1.838     albertel 13777: 	my ($lonid) = @_;
                   13778: 	return $hostname{$lonid};
                   13779:     }
1.845     albertel 13780: 
1.838     albertel 13781:     sub all_hostnames {
1.852     albertel 13782: 	&load_hosts_tab() if (!$loaded);
                   13783: 
1.838     albertel 13784: 	return %hostname;
                   13785:     }
1.845     albertel 13786: 
1.888     albertel 13787:     sub all_names {
1.1172.2.70  raeburn  13788:         my ($ignore_cache,$nocache) = @_;
                   13789: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13790: 
                   13791: 	return %name_to_host;
                   13792:     }
                   13793: 
1.974     raeburn  13794:     sub all_host_domain {
                   13795:         &load_hosts_tab() if (!$loaded);
                   13796:         return %hostdom;
                   13797:     }
                   13798: 
1.845     albertel 13799:     sub is_library {
1.852     albertel 13800: 	&load_hosts_tab() if (!$loaded);
                   13801: 
1.845     albertel 13802: 	return exists($libserv{$_[0]});
                   13803:     }
                   13804: 
                   13805:     sub all_library {
1.852     albertel 13806: 	&load_hosts_tab() if (!$loaded);
                   13807: 
1.845     albertel 13808: 	return %libserv;
                   13809:     }
                   13810: 
1.1062    droeschl 13811:     sub unique_library {
                   13812: 	#2x reverse removes all hostnames that appear more than once
                   13813:         my %unique = reverse &all_library();
                   13814:         return reverse %unique;
                   13815:     }
                   13816: 
1.841     albertel 13817:     sub get_servers {
1.852     albertel 13818: 	&load_hosts_tab() if (!$loaded);
                   13819: 
1.841     albertel 13820: 	my ($domain,$type) = @_;
                   13821: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13822: 	                                          : %hostname;
                   13823: 	my %result;
1.842     albertel 13824: 	if (ref($domain) eq 'ARRAY') {
                   13825: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13826: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13827: 		    $result{$host} = $hostname;
                   13828: 		}
                   13829: 	    }
                   13830: 	} else {
                   13831: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13832: 		if ($hostdom{$host} eq $domain) {
                   13833: 		    $result{$host} = $hostname;
                   13834: 		}
1.841     albertel 13835: 	    }
                   13836: 	}
                   13837: 	return %result;
                   13838:     }
1.845     albertel 13839: 
1.1062    droeschl 13840:     sub get_unique_servers {
                   13841:         my %unique = reverse &get_servers(@_);
                   13842: 	return reverse %unique;
                   13843:     }
                   13844: 
1.844     albertel 13845:     sub host_domain {
1.852     albertel 13846: 	&load_hosts_tab() if (!$loaded);
                   13847: 
1.844     albertel 13848: 	my ($lonid) = @_;
                   13849: 	return $hostdom{$lonid};
                   13850:     }
                   13851: 
1.841     albertel 13852:     sub all_domains {
1.852     albertel 13853: 	&load_hosts_tab() if (!$loaded);
                   13854: 
1.841     albertel 13855: 	my %seen;
                   13856: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13857: 	return @uniq;
                   13858:     }
1.1074    raeburn  13859: 
                   13860:     sub internet_dom {
                   13861:         &load_hosts_tab() if (!$loaded);
                   13862: 
                   13863:         my ($lonid) = @_;
                   13864:         return $internetdom{$lonid};
                   13865:     }
1.1107    raeburn  13866: 
                   13867:     sub is_LC_dns {
                   13868:         &load_hosts_tab() if (!$loaded);
                   13869: 
                   13870:         my ($hostname) = @_;
                   13871:         return exists($LC_dns_serv{$hostname});
                   13872:     }
                   13873: 
1.1       albertel 13874: }
                   13875: 
1.847     albertel 13876: { 
                   13877:     my %iphost;
1.856     albertel 13878:     my %name_to_ip;
                   13879:     my %lonid_to_ip;
1.869     albertel 13880: 
1.847     albertel 13881:     sub get_hosts_from_ip {
                   13882: 	my ($ip) = @_;
                   13883: 	my %iphosts = &get_iphost();
                   13884: 	if (ref($iphosts{$ip})) {
                   13885: 	    return @{$iphosts{$ip}};
                   13886: 	}
                   13887: 	return;
1.839     albertel 13888:     }
1.864     albertel 13889:     
                   13890:     sub reset_hosts_ip_info {
                   13891: 	undef(%iphost);
                   13892: 	undef(%name_to_ip);
                   13893: 	undef(%lonid_to_ip);
                   13894:     }
1.856     albertel 13895: 
                   13896:     sub get_host_ip {
                   13897: 	my ($lonid) = @_;
                   13898: 	if (exists($lonid_to_ip{$lonid})) {
                   13899: 	    return $lonid_to_ip{$lonid};
                   13900: 	}
                   13901: 	my $name=&hostname($lonid);
                   13902:    	my $ip = gethostbyname($name);
                   13903: 	return if (!$ip || length($ip) ne 4);
                   13904: 	$ip=inet_ntoa($ip);
                   13905: 	$name_to_ip{$name}   = $ip;
                   13906: 	$lonid_to_ip{$lonid} = $ip;
                   13907: 	return $ip;
                   13908:     }
1.847     albertel 13909:     
                   13910:     sub get_iphost {
1.1172.2.70  raeburn  13911: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13912: 
1.869     albertel 13913: 	if (!$ignore_cache) {
                   13914: 	    if (%iphost) {
                   13915: 		return %iphost;
                   13916: 	    }
                   13917: 	    my ($ip_info,$cached)=
                   13918: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13919: 	    if ($cached) {
                   13920: 		%iphost      = %{$ip_info->[0]};
                   13921: 		%name_to_ip  = %{$ip_info->[1]};
                   13922: 		%lonid_to_ip = %{$ip_info->[2]};
                   13923: 		return %iphost;
                   13924: 	    }
                   13925: 	}
1.894     albertel 13926: 
                   13927: 	# get yesterday's info for fallback
                   13928: 	my %old_name_to_ip;
                   13929: 	my ($ip_info,$cached)=
                   13930: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13931: 	if ($cached) {
                   13932: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13933: 	}
                   13934: 
1.1172.2.70  raeburn  13935: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13936: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13937: 	    my $ip;
                   13938: 	    if (!exists($name_to_ip{$name})) {
                   13939: 		$ip = gethostbyname($name);
                   13940: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13941: 		    if (defined($old_name_to_ip{$name})) {
                   13942: 			$ip = $old_name_to_ip{$name};
                   13943: 			&logthis("Can't find $name defaulting to old $ip");
                   13944: 		    } else {
                   13945: 			&logthis("Name $name no IP found");
                   13946: 			next;
                   13947: 		    }
                   13948: 		} else {
                   13949: 		    $ip=inet_ntoa($ip);
1.847     albertel 13950: 		}
                   13951: 		$name_to_ip{$name} = $ip;
                   13952: 	    } else {
                   13953: 		$ip = $name_to_ip{$name};
1.653     albertel 13954: 	    }
1.888     albertel 13955: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13956: 		$lonid_to_ip{$id} = $ip;
                   13957: 	    }
                   13958: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13959: 	}
1.1172.2.70  raeburn  13960:         unless ($nocache) {
                   13961: 	    &do_cache_new('iphost','iphost',
                   13962: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13963: 		          48*60*60);
                   13964:         }
1.869     albertel 13965: 
1.847     albertel 13966: 	return %iphost;
1.598     albertel 13967:     }
                   13968: 
1.992     raeburn  13969:     #
                   13970:     #  Given a DNS returns the loncapa host name for that DNS 
                   13971:     # 
                   13972:     sub host_from_dns {
                   13973:         my ($dns) = @_;
                   13974:         my @hosts;
                   13975:         my $ip;
                   13976: 
1.993     raeburn  13977:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13978:             $ip = $name_to_ip{$dns};
                   13979:         }
                   13980:         if (!$ip) {
                   13981:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13982:             if (length($ip) == 4) { 
                   13983: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13984:             }
                   13985:         }
                   13986:         if ($ip) {
                   13987: 	    @hosts = get_hosts_from_ip($ip);
                   13988: 	    return $hosts[0];
                   13989:         }
                   13990:         return undef;
1.986     foxr     13991:     }
1.992     raeburn  13992: 
1.1074    raeburn  13993:     sub get_internet_names {
                   13994:         my ($lonid) = @_;
                   13995:         return if ($lonid eq '');
                   13996:         my ($idnref,$cached)=
                   13997:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13998:         if ($cached) {
                   13999:             return $idnref;
                   14000:         }
                   14001:         my $ip = &get_host_ip($lonid);
                   14002:         my @hosts = &get_hosts_from_ip($ip);
                   14003:         my %iphost = &get_iphost();
                   14004:         my (@idns,%seen);
                   14005:         foreach my $id (@hosts) {
                   14006:             my $dom = &host_domain($id);
                   14007:             my $prim_id = &domain($dom,'primary');
                   14008:             my $prim_ip = &get_host_ip($prim_id);
                   14009:             next if ($seen{$prim_ip});
                   14010:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14011:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14012:                     my $intdom = &internet_dom($id);
                   14013:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14014:                         push(@idns,$intdom);
                   14015:                     }
                   14016:                 }
                   14017:             }
                   14018:             $seen{$prim_ip} = 1;
                   14019:         }
1.1172.2.23  raeburn  14020:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14021:     }
                   14022: 
1.986     foxr     14023: }
                   14024: 
1.1079    raeburn  14025: sub all_loncaparevs {
1.1172.2.39  raeburn  14026:     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  14027: }
                   14028: 
1.1172.2.27  raeburn  14029: # ------------------------------------------------------- Read loncaparev table
                   14030: {
                   14031:     sub load_loncaparevs {
                   14032:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14033:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14034:                 while (my $configline=<$config>) {
                   14035:                     chomp($configline);
                   14036:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14037:                     $loncaparevs{$hostid}=$loncaparev;
                   14038:                 }
                   14039:                 close($config);
                   14040:             }
                   14041:         }
                   14042:     }
                   14043: }
                   14044: 
                   14045: # ----------------------------------------------------- Read serverhostID table
                   14046: {
                   14047:     sub load_serverhomeIDs {
                   14048:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14049:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14050:                 while (my $configline=<$config>) {
                   14051:                     chomp($configline);
                   14052:                     my ($name,$id)=split(/:/,$configline);
                   14053:                     $serverhomeIDs{$name}=$id;
                   14054:                 }
                   14055:                 close($config);
                   14056:             }
                   14057:         }
                   14058:     }
                   14059: }
                   14060: 
                   14061: 
1.862     albertel 14062: BEGIN {
                   14063: 
                   14064: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14065:     unless ($readit) {
                   14066: {
                   14067:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14068:     %perlvar = (%perlvar,%{$configvars});
                   14069: }
                   14070: 
                   14071: 
1.1       albertel 14072: # ------------------------------------------------------ Read spare server file
                   14073: {
1.1172.2.96  raeburn  14074:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14075: 
                   14076:     while (my $configline=<$config>) {
                   14077:        chomp($configline);
1.284     matthew  14078:        if ($configline) {
1.784     albertel 14079: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14080: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14081: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14082:        }
                   14083:     }
1.448     albertel 14084:     close($config);
1.1       albertel 14085: }
1.11      www      14086: # ------------------------------------------------------------ Read permissions
                   14087: {
1.1172.2.96  raeburn  14088:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14089: 
                   14090:     while (my $configline=<$config>) {
1.448     albertel 14091: 	chomp($configline);
                   14092: 	if ($configline) {
                   14093: 	    my ($role,$perm)=split(/ /,$configline);
                   14094: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14095: 	}
1.11      www      14096:     }
1.448     albertel 14097:     close($config);
1.11      www      14098: }
                   14099: 
                   14100: # -------------------------------------------- Read plain texts for permissions
                   14101: {
1.1172.2.96  raeburn  14102:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14103: 
                   14104:     while (my $configline=<$config>) {
1.448     albertel 14105: 	chomp($configline);
                   14106: 	if ($configline) {
1.742     raeburn  14107: 	    my ($short,@plain)=split(/:/,$configline);
                   14108:             %{$prp{$short}} = ();
                   14109: 	    if (@plain > 0) {
                   14110:                 $prp{$short}{'std'} = $plain[0];
                   14111:                 for (my $i=1; $i<@plain; $i++) {
                   14112:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14113:                 }
                   14114:             }
1.448     albertel 14115: 	}
1.135     www      14116:     }
1.448     albertel 14117:     close($config);
1.135     www      14118: }
                   14119: 
                   14120: # ---------------------------------------------------------- Read package table
                   14121: {
1.1172.2.96  raeburn  14122:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14123: 
                   14124:     while (my $configline=<$config>) {
1.483     albertel 14125: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14126: 	chomp($configline);
                   14127: 	my ($short,$plain)=split(/:/,$configline);
                   14128: 	my ($pack,$name)=split(/\&/,$short);
                   14129: 	if ($plain ne '') {
                   14130: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14131: 	    $packagetab{$short}=$plain; 
                   14132: 	}
1.11      www      14133:     }
1.448     albertel 14134:     close($config);
1.329     matthew  14135: }
                   14136: 
1.1172.2.27  raeburn  14137: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14138: 
1.1172.2.27  raeburn  14139: &load_loncaparevs();
                   14140: 
                   14141: # ------------------------------------------------------- Read serverhostID table
                   14142: 
                   14143: &load_serverhomeIDs();
1.1074    raeburn  14144: 
1.1172.2.27  raeburn  14145: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14146: {
                   14147:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14148:     if (-e $file) {
                   14149:         my $parser = HTML::LCParser->new($file);
                   14150:         while (my $token = $parser->get_token()) {
                   14151:             if ($token->[0] eq 'S') {
                   14152:                 my $item = $token->[1];
                   14153:                 my $name = $token->[2]{'name'};
                   14154:                 my $value = $token->[2]{'value'};
                   14155:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14156:                     my $release = $parser->get_text();
                   14157:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14158:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14159:                 }
                   14160:             }
                   14161:         }
                   14162:     }
1.1073    raeburn  14163: }
                   14164: 
1.1138    raeburn  14165: # ---------------------------------------------------------- Read managers table
                   14166: {
                   14167:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14168:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14169:             while (my $configline=<$config>) {
                   14170:                 chomp($configline);
                   14171:                 next if ($configline =~ /^\#/);
                   14172:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14173:                     $managerstab{$configline} = 1;
                   14174:                 }
                   14175:             }
                   14176:             close($config);
                   14177:         }
                   14178:     }
                   14179: }
                   14180: 
1.329     matthew  14181: # ------------- set up temporary directory
                   14182: {
1.1117    foxr     14183:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14184: 
1.11      www      14185: }
                   14186: 
1.1172.2.104  raeburn  14187: # ------------- set default texengine (domain default overrides this)
                   14188: {
                   14189:     $deftex = LONCAPA::texengine();
                   14190: }
                   14191: 
1.1172.2.114  raeburn  14192: # ------------- set default minimum length for passwords for internal auth users
                   14193: {
                   14194:     $passwdmin = LONCAPA::passwd_min();
                   14195: }
                   14196: 
1.794     albertel 14197: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14198: 				'compress_threshold'=> 20_000,
                   14199:  			        });
1.185     www      14200: 
1.281     www      14201: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14202: $dumpcount=0;
1.958     www      14203: $locknum=0;
1.22      www      14204: 
1.163     harris41 14205: &logtouch();
1.672     albertel 14206: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14207: $readit=1;
1.564     albertel 14208:     {
                   14209: 	use integer;
                   14210: 	my $test=(2**32)+1;
1.568     albertel 14211: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14212: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14213:     }
1.195     www      14214: }
1.1       albertel 14215: }
1.179     www      14216: 
1.1       albertel 14217: 1;
1.191     harris41 14218: __END__
                   14219: 
1.243     albertel 14220: =pod
                   14221: 
1.191     harris41 14222: =head1 NAME
                   14223: 
1.243     albertel 14224: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14225: 
                   14226: =head1 SYNOPSIS
                   14227: 
1.243     albertel 14228: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14229: 
                   14230:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14231: 
1.243     albertel 14232: Common parameters:
                   14233: 
                   14234: =over 4
                   14235: 
                   14236: =item *
                   14237: 
                   14238: $uname : an internal username (if $cname expecting a course Id specifically)
                   14239: 
                   14240: =item *
                   14241: 
                   14242: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14243: 
                   14244: =item *
                   14245: 
                   14246: $symb : a resource instance identifier
                   14247: 
                   14248: =item *
                   14249: 
                   14250: $namespace : the name of a .db file that contains the data needed or
                   14251: being set.
                   14252: 
                   14253: =back
                   14254: 
1.394     bowersj2 14255: =head1 OVERVIEW
1.191     harris41 14256: 
1.394     bowersj2 14257: lonnet provides subroutines which interact with the
                   14258: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14259: about classes, users, and resources.
1.243     albertel 14260: 
                   14261: For many of these objects you can also use this to store data about
                   14262: them or modify them in various ways.
1.191     harris41 14263: 
1.394     bowersj2 14264: =head2 Symbs
1.191     harris41 14265: 
1.394     bowersj2 14266: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14267: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14268: map, the resource number of the resource in the map, and the URL of
                   14269: the resource itself. The latter is somewhat redundant, but might help
                   14270: if maps change.
                   14271: 
                   14272: An example is
                   14273: 
                   14274:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14275: 
                   14276: The respective map entry is
                   14277: 
                   14278:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14279:   title="Problem 2">
                   14280:  </resource>
                   14281: 
                   14282: Symbs are used by the random number generator, as well as to store and
                   14283: restore data specific to a certain instance of for example a problem.
                   14284: 
                   14285: =head2 Storing And Retrieving Data
                   14286: 
                   14287: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14288: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14289: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14290: is is the non-critical message twin of cstore. These functions are for
                   14291: handlers to store a perl hash to a user's permanent data space in an
                   14292: easy manner, and to retrieve it again on another call. It is expected
                   14293: that a handler would use this once at the beginning to retrieve data,
                   14294: and then again once at the end to send only the new data back.
                   14295: 
                   14296: The data is stored in the user's data directory on the user's
                   14297: homeserver under the ID of the course.
                   14298: 
                   14299: The hash that is returned by restore will have all of the previous
                   14300: value for all of the elements of the hash.
                   14301: 
                   14302: Example:
                   14303: 
                   14304:  #creating a hash
                   14305:  my %hash;
                   14306:  $hash{'foo'}='bar';
                   14307: 
                   14308:  #storing it
                   14309:  &Apache::lonnet::cstore(\%hash);
                   14310: 
                   14311:  #changing a value
                   14312:  $hash{'foo'}='notbar';
                   14313: 
                   14314:  #adding a new value
                   14315:  $hash{'bar'}='foo';
                   14316:  &Apache::lonnet::cstore(\%hash);
                   14317: 
                   14318:  #retrieving the hash
                   14319:  my %history=&Apache::lonnet::restore();
                   14320: 
                   14321:  #print the hash
                   14322:  foreach my $key (sort(keys(%history))) {
                   14323:    print("\%history{$key} = $history{$key}");
                   14324:  }
                   14325: 
                   14326: Will print out:
1.191     harris41 14327: 
1.394     bowersj2 14328:  %history{1:foo} = bar
                   14329:  %history{1:keys} = foo:timestamp
                   14330:  %history{1:timestamp} = 990455579
                   14331:  %history{2:bar} = foo
                   14332:  %history{2:foo} = notbar
                   14333:  %history{2:keys} = foo:bar:timestamp
                   14334:  %history{2:timestamp} = 990455580
                   14335:  %history{bar} = foo
                   14336:  %history{foo} = notbar
                   14337:  %history{timestamp} = 990455580
                   14338:  %history{version} = 2
                   14339: 
                   14340: Note that the special hash entries C<keys>, C<version> and
                   14341: C<timestamp> were added to the hash. C<version> will be equal to the
                   14342: total number of versions of the data that have been stored. The
                   14343: C<timestamp> attribute will be the UNIX time the hash was
                   14344: stored. C<keys> is available in every historical section to list which
                   14345: keys were added or changed at a specific historical revision of a
                   14346: hash.
                   14347: 
                   14348: B<Warning>: do not store the hash that restore returns directly. This
                   14349: will cause a mess since it will restore the historical keys as if the
                   14350: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14351: 
1.394     bowersj2 14352: Calling convention:
1.191     harris41 14353: 
1.1172.2.27  raeburn  14354:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14355:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14356: 
1.394     bowersj2 14357: For more detailed information, see lonnet specific documentation.
1.191     harris41 14358: 
1.394     bowersj2 14359: =head1 RETURN MESSAGES
1.191     harris41 14360: 
1.394     bowersj2 14361: =over 4
1.191     harris41 14362: 
1.394     bowersj2 14363: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14364: 
1.394     bowersj2 14365: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14366: when the connection is brought back up
1.191     harris41 14367: 
1.394     bowersj2 14368: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14369: for later delivery
1.191     harris41 14370: 
1.967     bisitz   14371: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14372: 
1.394     bowersj2 14373: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14374: that was requested
1.191     harris41 14375: 
1.243     albertel 14376: =back
1.191     harris41 14377: 
1.243     albertel 14378: =head1 PUBLIC SUBROUTINES
1.191     harris41 14379: 
1.243     albertel 14380: =head2 Session Environment Functions
1.191     harris41 14381: 
1.243     albertel 14382: =over 4
1.191     harris41 14383: 
1.394     bowersj2 14384: =item * 
                   14385: X<appenv()>
1.949     raeburn  14386: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14387: the user envirnoment file, and will be restored for each access this
1.620     albertel 14388: user makes during this session, also modifies the %env for the current
1.949     raeburn  14389: process. Optional rolesarrayref - if defined contains a reference to an array
                   14390: of roles which are exempt from the restriction on modifying user.role entries 
                   14391: in the user's environment.db and in %env.    
1.191     harris41 14392: 
                   14393: =item *
1.394     bowersj2 14394: X<delenv()>
1.987     raeburn  14395: B<delenv($delthis,$regexp)>: removes all items from the session
                   14396: environment file that begin with $delthis. If the 
                   14397: optional second arg - $regexp - is true, $delthis is treated as a 
                   14398: regular expression, otherwise \Q$delthis\E is used. 
                   14399: The values are also deleted from the current processes %env.
1.191     harris41 14400: 
1.795     albertel 14401: =item * get_env_multiple($name) 
                   14402: 
                   14403: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14404: values may be defined and end up as an array ref.
                   14405: 
                   14406: returns an array of values
                   14407: 
1.243     albertel 14408: =back
                   14409: 
                   14410: =head2 User Information
1.191     harris41 14411: 
1.243     albertel 14412: =over 4
1.191     harris41 14413: 
                   14414: =item *
1.394     bowersj2 14415: X<queryauthenticate()>
                   14416: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14417: authentication scheme
                   14418: 
                   14419: =item *
1.394     bowersj2 14420: X<authenticate()>
1.1073    raeburn  14421: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14422: authenticate user from domain's lib servers (first use the current
                   14423: one). C<$upass> should be the users password.
1.1073    raeburn  14424: $checkdefauth is optional (value is 1 if a check should be made to
                   14425:    authenticate user using default authentication method, and allow
                   14426:    account creation if username does not have account in the domain).
                   14427: $clientcancheckhost is optional (value is 1 if checking whether the
                   14428:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14429: 
                   14430: =item *
1.394     bowersj2 14431: X<homeserver()>
                   14432: B<homeserver($uname,$udom)>: find the server which has
                   14433: the user's directory and files (there must be only one), this caches
                   14434: the answer, and also caches if there is a borken connection.
1.191     harris41 14435: 
                   14436: =item *
1.394     bowersj2 14437: X<idget()>
                   14438: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14439: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14440: username, and only 1 username per ID in a specific domain) (returns
                   14441: hash: id=>name,id=>name)
1.191     harris41 14442: 
                   14443: =item *
1.394     bowersj2 14444: X<idrget()>
                   14445: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14446: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14447: 
                   14448: =item *
1.394     bowersj2 14449: X<idput()>
                   14450: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14451: 
                   14452: =item *
1.394     bowersj2 14453: X<rolesinit()>
1.1169    droeschl 14454: B<rolesinit($udom,$username)>: get user privileges.
                   14455: returns user role, first access and timer interval hashes
1.243     albertel 14456: 
                   14457: =item *
1.1171    droeschl 14458: X<privileged()>
                   14459: B<privileged($username,$domain)>: returns a true if user has a
                   14460: privileged and active role (i.e. su or dc), false otherwise.
                   14461: 
                   14462: =item *
1.551     albertel 14463: X<getsection()>
                   14464: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14465: course $cname, return section name/number or '' for "not in course"
                   14466: and '-1' for "no section"
                   14467: 
                   14468: =item *
1.394     bowersj2 14469: X<userenvironment()>
                   14470: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14471: passed in @what from the requested user's environment, returns a hash
                   14472: 
1.858     raeburn  14473: =item * 
                   14474: X<userlog_query()>
1.859     albertel 14475: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14476: activity.log file. %filters defines filters applied when parsing the
                   14477: log file. These can be start or end timestamps, or the type of action
                   14478: - log to look for Login or Logout events, check for Checkin or
                   14479: Checkout, role for role selection. The response is in the form
                   14480: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14481: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14482: 
1.243     albertel 14483: =back
                   14484: 
                   14485: =head2 User Roles
                   14486: 
                   14487: =over 4
                   14488: 
                   14489: =item *
                   14490: 
1.1172.2.65  raeburn  14491: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14492: returns codes for allowed actions.
                   14493: 
                   14494: The first argument is required, all others are optional.
                   14495: 
                   14496: $priv is the privilege being checked.
                   14497: $uri contains additional information about what is being checked for access (e.g.,
                   14498: URL, course ID etc.).
                   14499: $symb is the unique resource instance identifier in a course; if needed,
                   14500: but not provided, it will be retrieved via a call to &symbread().
                   14501: $role is the role for which a priv is being checked (only used if priv is evb).
                   14502: $clientip is the user's IP address (only used when checking for access to portfolio
                   14503: files).
                   14504: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14505: prevents recursive calls to &allowed.
                   14506: 
1.243     albertel 14507:  F: full access
                   14508:  U,I,K: authentication modes (cxx only)
                   14509:  '': forbidden
                   14510:  1: user needs to choose course
                   14511:  2: browse allowed
1.766     albertel 14512:  A: passphrase authentication needed
1.1172.2.65  raeburn  14513:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14514: 
                   14515: =item *
                   14516: 
1.1172.2.13  raeburn  14517: constructaccess($url,$setpriv) : check for access to construction space URL
                   14518: 
                   14519: See if the owner domain and name in the URL match those in the
                   14520: expected environment.  If so, return three element list
                   14521: ($ownername,$ownerdomain,$ownerhome).
                   14522: 
                   14523: Otherwise return the null string.
                   14524: 
                   14525: If second argument 'setpriv' is true, it assigns the privileges,
                   14526: and returns the same three element list, unless the owner has
                   14527: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14528: in which case the null string is returned.
                   14529: 
                   14530: =item *
                   14531: 
1.1172.2.84  raeburn  14532: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14533: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14534: for system, domain, and course level. $uname and $udom are optional (current
                   14535: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14536: 
                   14537: =item *
                   14538: 
1.988     raeburn  14539: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14540: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14541: $type is Course (default) or Community.
1.988     raeburn  14542: If $forcedefault evaluates to true, text returned will be default 
                   14543: text for $type. Otherwise, if this is a course, the text returned 
                   14544: will be a custom name for the role (if defined in the course's 
                   14545: environment).  If no custom name is defined the default is returned.
                   14546:    
1.832     raeburn  14547: =item *
                   14548: 
1.1172.2.23  raeburn  14549: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14550: All arguments are optional. Returns a hash of a roles, either for
                   14551: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14552: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14553: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14554: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14555: For each key, value is set to colon-separated start and end times for
                   14556: the role.  If no username and domain are specified, will default to
1.934     raeburn  14557: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14558: of role statuses (active, future or previous), roles 
                   14559: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14560: to restrict the list of roles reported. If no array ref is 
                   14561: provided for types, will default to return only active roles.
1.834     albertel 14562: 
1.1172.2.13  raeburn  14563: =item *
                   14564: 
                   14565: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14566: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14567: 
                   14568: Additional optional arguments are: $type (if role checking is to be restricted
                   14569: to certain user status types -- previous (expired roles), active (currently
                   14570: available roles) or future (roles available in the future), and
                   14571: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14572: have active Domain Coordinator role in course's domain or in additional
                   14573: domains (specified in 'Domains to check for privileged users' in course
                   14574: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14575: 
                   14576: =item *
                   14577: 
                   14578: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14579: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14580: $possdomains and $possroles are optional array refs -- to domains to check and
                   14581: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14582: users' roles.db to check for a dc or su role in any domain. This can be
                   14583: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14584: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14585: this then allows &privileged_by_domain() to be used, which caches the identity
                   14586: of privileged users, eliminating the need for repeated calls to &dump().
                   14587: 
                   14588: =item *
                   14589: 
                   14590: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14591: where the outer hash keys are domains specified in the $possdomains array ref,
                   14592: next inner hash keys are privileged roles specified in the $roles array ref,
                   14593: and the innermost hash contains key = value pairs for username:domain = end:start
                   14594: for active or future "privileged" users with that role in that domain. To avoid
                   14595: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14596: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14597: 
1.243     albertel 14598: =back
                   14599: 
                   14600: =head2 User Modification
                   14601: 
                   14602: =over 4
                   14603: 
                   14604: =item *
                   14605: 
1.957     raeburn  14606: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14607: user for the level given by URL.  Optional start and end dates (leave empty
                   14608: string or zero for "no date")
1.191     harris41 14609: 
                   14610: =item *
                   14611: 
1.243     albertel 14612: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14613: change a users, password, possible return values are: ok,
                   14614: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14615: refused
1.191     harris41 14616: 
                   14617: =item *
                   14618: 
1.243     albertel 14619: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14620: 
                   14621: =item *
                   14622: 
1.1058    raeburn  14623: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14624:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14625: 
                   14626: will update user information (firstname,middlename,lastname,generation,
                   14627: permanentemail), and if forceid is true, student/employee ID also.
                   14628: A user's institutional affiliation(s) can also be updated.
                   14629: User information fields will not be overwritten with empty entries 
                   14630: unless the field is included in the $candelete array reference.
                   14631: This array is included when a single user is modified via "Manage Users",
                   14632: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14633: 
                   14634: =item *
                   14635: 
1.286     matthew  14636: modifystudent
                   14637: 
1.957     raeburn  14638: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14639: The course id is resolved based on the current user's environment.  
                   14640: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14641: associated with a course.
                   14642: 
1.297     matthew  14643: This call is essentially a wrapper for lonnet::modifyuser and
                   14644: lonnet::modify_student_enrollment
1.286     matthew  14645: 
                   14646: Inputs: 
                   14647: 
                   14648: =over 4
                   14649: 
1.957     raeburn  14650: =item B<$udom> Student's loncapa domain
1.286     matthew  14651: 
1.957     raeburn  14652: =item B<$uname> Student's loncapa login name
1.286     matthew  14653: 
1.964     bisitz   14654: =item B<$uid> Student/Employee ID
1.286     matthew  14655: 
1.957     raeburn  14656: =item B<$umode> Student's authentication mode
1.286     matthew  14657: 
1.957     raeburn  14658: =item B<$upass> Student's password
1.286     matthew  14659: 
1.957     raeburn  14660: =item B<$first> Student's first name
1.286     matthew  14661: 
1.957     raeburn  14662: =item B<$middle> Student's middle name
1.286     matthew  14663: 
1.957     raeburn  14664: =item B<$last> Student's last name
1.286     matthew  14665: 
1.957     raeburn  14666: =item B<$gene> Student's generation
1.286     matthew  14667: 
1.957     raeburn  14668: =item B<$usec> Student's section in course
1.286     matthew  14669: 
                   14670: =item B<$end> Unix time of the roles expiration
                   14671: 
                   14672: =item B<$start> Unix time of the roles start date
                   14673: 
                   14674: =item B<$forceid> If defined, allow $uid to be changed
                   14675: 
                   14676: =item B<$desiredhome> server to use as home server for student
                   14677: 
1.957     raeburn  14678: =item B<$email> Student's permanent e-mail address
                   14679: 
                   14680: =item B<$type> Type of enrollment (auto or manual)
                   14681: 
1.963     raeburn  14682: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14683: 
                   14684: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14685: 
1.963     raeburn  14686: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14687: 
1.963     raeburn  14688: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14689: 
1.1172.2.19  raeburn  14690: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14691: 
                   14692: =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  14693: 
1.286     matthew  14694: =back
1.297     matthew  14695: 
                   14696: =item *
                   14697: 
                   14698: modify_student_enrollment
                   14699: 
1.1172.2.31  raeburn  14700: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14701: 'role.request.course' must be defined for this function to proceed.
                   14702: 
                   14703: Inputs:
                   14704: 
                   14705: =over 4
                   14706: 
1.1172.2.31  raeburn  14707: =item $udom, student's domain
1.297     matthew  14708: 
1.1172.2.31  raeburn  14709: =item $uname, student's name
1.297     matthew  14710: 
1.1172.2.31  raeburn  14711: =item $uid, student's user id
1.297     matthew  14712: 
1.1172.2.31  raeburn  14713: =item $first, student's first name
1.297     matthew  14714: 
                   14715: =item $middle
                   14716: 
                   14717: =item $last
                   14718: 
                   14719: =item $gene
                   14720: 
                   14721: =item $usec
                   14722: 
                   14723: =item $end
                   14724: 
                   14725: =item $start
                   14726: 
1.957     raeburn  14727: =item $type
                   14728: 
                   14729: =item $locktype
                   14730: 
                   14731: =item $cid
                   14732: 
                   14733: =item $selfenroll
                   14734: 
                   14735: =item $context
                   14736: 
1.1172.2.19  raeburn  14737: =item $credits, number of credits student will earn from this class
                   14738: 
1.1172.2.76  raeburn  14739: =item $instsec, institutional course section code for student
                   14740: 
1.297     matthew  14741: =back
                   14742: 
1.191     harris41 14743: 
                   14744: =item *
                   14745: 
1.243     albertel 14746: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14747: custom role; give a custom role to a user for the level given by URL.  Specify
                   14748: name and domain of role author, and role name
1.191     harris41 14749: 
                   14750: =item *
                   14751: 
1.243     albertel 14752: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14753: 
                   14754: =item *
                   14755: 
1.243     albertel 14756: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14757: 
                   14758: =back
                   14759: 
                   14760: =head2 Course Infomation
                   14761: 
                   14762: =over 4
1.191     harris41 14763: 
                   14764: =item *
                   14765: 
1.1118    foxr     14766: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14767: specified course id, including all environment settings for the
                   14768: course, the description of the course will be in the hash under the
                   14769: key 'description'
1.191     harris41 14770: 
1.1118    foxr     14771: $options is an optional parameter that if supplied is a hash reference that controls
                   14772: what how this function works.  It has the following key/values:
                   14773: 
                   14774: =over 4
                   14775: 
                   14776: =item freshen_cache
                   14777: 
                   14778: If defined, and the environment cache for the course is valid, it is 
                   14779: returned in the returned hash.
                   14780: 
                   14781: =item one_time
                   14782: 
                   14783: If defined, the last cache time is set to _now_
                   14784: 
                   14785: =item user
                   14786: 
                   14787: If defined, the supplied username is used instead of the current user.
                   14788: 
                   14789: 
                   14790: =back
                   14791: 
1.191     harris41 14792: =item *
                   14793: 
1.624     albertel 14794: resdata($name,$domain,$type,@which) : request for current parameter
                   14795: setting for a specific $type, where $type is either 'course' or 'user',
                   14796: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14797: answers for 10 minutes.
1.243     albertel 14798: 
1.877     foxr     14799: =item *
                   14800: 
                   14801: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14802: data base, returning a hash that is keyed by the resource name and has
                   14803: values that are the resource value.  I believe that the timestamps and
                   14804: versions are also returned.
                   14805: 
1.1172.2.31  raeburn  14806: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14807: supplemental content area. This routine caches the number of files for
                   14808: 10 minutes.
                   14809: 
1.243     albertel 14810: =back
                   14811: 
                   14812: =head2 Course Modification
                   14813: 
                   14814: =over 4
1.191     harris41 14815: 
                   14816: =item *
                   14817: 
1.243     albertel 14818: writecoursepref($courseid,%prefs) : write preferences (environment
                   14819: database) for a course
1.191     harris41 14820: 
                   14821: =item *
                   14822: 
1.1011    raeburn  14823: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14824: 
                   14825: =item *
                   14826: 
1.1038    raeburn  14827: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14828: 
1.1167    droeschl 14829: =item *
                   14830: 
                   14831: is_course($courseid), is_course($cdom, $cnum)
                   14832: 
                   14833: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14834: two component version $cdom, $cnum. It checks if the specified course exists.
                   14835: 
                   14836: Returns:
                   14837:     undef if the course doesn't exist, otherwise
                   14838:     in scalar context the combined courseid.
                   14839:     in list context the two components of the course identifier, domain and 
                   14840:     courseid.    
                   14841: 
1.243     albertel 14842: =back
                   14843: 
1.1172.2.109  raeburn  14844: =head2 Bubblesheet Configuration
                   14845: 
                   14846: =over 4
                   14847: 
                   14848: =item *
                   14849: 
                   14850: get_scantron_config($which)
                   14851: 
                   14852: $which - the name of the configuration to parse from the file.
                   14853: 
                   14854: Parses and returns the bubblesheet configuration line selected as a
                   14855: hash of configuration file fields.
                   14856: 
                   14857: 
                   14858: Returns:
                   14859:     If the named configuration is not in the file, an empty
                   14860:     hash is returned.
                   14861: 
                   14862:     a hash with the fields
                   14863:       name         - internal name for the this configuration setup
                   14864:       description  - text to display to operator that describes this config
                   14865:       CODElocation - if 0 or the string 'none'
                   14866:                           - no CODE exists for this config
                   14867:                      if -1 || the string 'letter'
                   14868:                           - a CODE exists for this config and is
                   14869:                             a string of letters
                   14870:                      Unsupported value (but planned for future support)
                   14871:                           if a positive integer
                   14872:                                - The CODE exists as the first n items from
                   14873:                                  the question section of the form
                   14874:                           if the string 'number'
                   14875:                                - The CODE exists for this config and is
                   14876:                                  a string of numbers
                   14877:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14878:                      the CODE starts
                   14879:       CODElength  - length of the CODE
                   14880:       IDstart     - column where the student/employee ID starts
                   14881:       IDlength    - length of the student/employee ID info
                   14882:       Qstart      - column where the information from the bubbled
                   14883:                     'questions' start
                   14884:       Qlength     - number of columns comprising a single bubble line from
                   14885:                     the sheet. (usually either 1 or 10)
                   14886:       Qon         - either a single character representing the character used
                   14887:                     to signal a bubble was chosen in the positional setup, or
                   14888:                     the string 'letter' if the letter of the chosen bubble is
                   14889:                     in the final, or 'number' if a number representing the
                   14890:                     chosen bubble is in the file (1->A 0->J)
                   14891:       Qoff        - the character used to represent that a bubble was
                   14892:                     left blank
                   14893:       PaperID     - if the scanning process generates a unique number for each
                   14894:                     sheet scanned the column that this ID number starts in
                   14895:       PaperIDlength - number of columns that comprise the unique ID number
                   14896:                       for the sheet of paper
                   14897:       FirstName   - column that the first name starts in
                   14898:       FirstNameLength - number of columns that the first name spans
                   14899:       LastName    - column that the last name starts in
                   14900:       LastNameLength - number of columns that the last name spans
                   14901:       BubblesPerRow - number of bubbles available in each row used to
                   14902:                       bubble an answer. (If not specified, 10 assumed).
                   14903: 
                   14904: 
                   14905: =item *
                   14906: 
                   14907: get_scantronformat_file($cdom)
                   14908: 
                   14909: $cdom - the course's domain (optional); if not supplied, uses
                   14910: domain for current $env{'request.course.id'}.
                   14911: 
                   14912: Returns an array containing lines from the scantron format file for
                   14913: the domain of the course.
                   14914: 
                   14915: If a url for a custom.tab file is listed in domain's configuration.db,
                   14916: lines are from this file.
                   14917: 
                   14918: Otherwise, if a default.tab has been published in RES space by the
                   14919: domainconfig user, lines are from this file.
                   14920: 
                   14921: Otherwise, fall back to getting lines from the legacy file on the
                   14922: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14923: 
                   14924: =back
                   14925: 
1.243     albertel 14926: =head2 Resource Subroutines
                   14927: 
                   14928: =over 4
1.191     harris41 14929: 
                   14930: =item *
                   14931: 
1.243     albertel 14932: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14933: 
                   14934: =item *
                   14935: 
1.243     albertel 14936: repcopy($filename) : subscribes to the requested file, and attempts to
                   14937: replicate from the owning library server, Might return
1.607     raeburn  14938: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14939: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14940: resource. Expects the local filesystem pathname
                   14941: (/home/httpd/html/res/....)
                   14942: 
                   14943: =back
                   14944: 
                   14945: =head2 Resource Information
                   14946: 
                   14947: =over 4
1.191     harris41 14948: 
                   14949: =item *
                   14950: 
1.1172.2.28  raeburn  14951: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14952: and returns the value of a variety of different possible values,
                   14953: $varname should be a request string, and the other parameters can be
                   14954: used to specify who and what one is asking about. Ordinarily, $cid 
                   14955: does not need to be specified, as it is retrived from 
                   14956: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14957: within lonuserstate::loadmap() when initializing a course, before
                   14958: $env{'request.course.id'} has been set, so it needs to be provided
                   14959: in that one case.
1.243     albertel 14960: 
                   14961: Possible values for $varname are environment.lastname (or other item
                   14962: from the envirnment hash), user.name (or someother aspect about the
                   14963: user), resource.0.maxtries (or some other part and parameter of a
                   14964: resource)
1.204     albertel 14965: 
                   14966: =item *
                   14967: 
1.243     albertel 14968: directcondval($number) : get current value of a condition; reads from a state
                   14969: string
1.204     albertel 14970: 
                   14971: =item *
                   14972: 
1.243     albertel 14973: condval($condidx) : value of condition index based on state
1.204     albertel 14974: 
                   14975: =item *
                   14976: 
1.243     albertel 14977: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14978: resource's metadata, $what should be either a specific key, or either
                   14979: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14980: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14981: 
                   14982: this function automatically caches all requests
1.191     harris41 14983: 
                   14984: =item *
                   14985: 
1.243     albertel 14986: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14987: network of library servers; returns file handle of where SQL and regex results
                   14988: will be stored for query
1.191     harris41 14989: 
                   14990: =item *
                   14991: 
1.1172.2.66  raeburn  14992: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14993: return symbolic list entry (all arguments optional).
                   14994: 
                   14995: Args: filename is the filename (including path) for the file for which a symb
                   14996: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14997: to check access status if more than one resource was found in the bighash
                   14998: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14999: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15000: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15001: cause possible symbs to be checked to determine if they are subject to content
                   15002: blocking, if so they will not be included as possible symbs; possibles is a
                   15003: ref to a hash, which, as a side effect, will be populated with all possible
                   15004: symbs (content blocking not tested).
                   15005: 
1.243     albertel 15006: returns the data handle
1.191     harris41 15007: 
                   15008: =item *
                   15009: 
1.1172.2.17  raeburn  15010: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15011: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15012: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15013: on failure, user must be in a course, as it assumes the existence of
                   15014: the course initial hash, and uses $env('request.course.id'}.  The third
                   15015: arg is an optional reference to a scalar.  If this arg is passed in the
                   15016: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15017: encrypted; otherwise it will be null.
1.243     albertel 15018: 
1.191     harris41 15019: =item *
                   15020: 
1.243     albertel 15021: symbclean($symb) : removes versions numbers from a symb, returns the
                   15022: cleaned symb
1.191     harris41 15023: 
                   15024: =item *
                   15025: 
1.243     albertel 15026: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15027: course map, user must be in a course for it to work.
1.191     harris41 15028: 
                   15029: =item *
                   15030: 
1.243     albertel 15031: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15032: 
                   15033: =item *
                   15034: 
1.243     albertel 15035: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15036: a random seed, all arguments are optional, if they aren't sent it uses the
                   15037: environment to derive them. Note: if symb isn't sent and it can't get one
                   15038: from &symbread it will use the current time as its return value
1.191     harris41 15039: 
                   15040: =item *
                   15041: 
1.243     albertel 15042: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15043: unfakeable, receipt
1.191     harris41 15044: 
                   15045: =item *
                   15046: 
1.620     albertel 15047: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15048: 
                   15049: =item *
                   15050: 
1.243     albertel 15051: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15052: 
                   15053: =item *
                   15054: 
1.243     albertel 15055: 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 15056: 
                   15057: =item *
                   15058: 
1.243     albertel 15059: 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 15060: 
                   15061: =item *
                   15062: 
1.243     albertel 15063: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15064: 
                   15065: =item *
                   15066: 
1.243     albertel 15067: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15068: forcing spreadsheet to reevaluate the resource scores next time.
                   15069: 
1.1172.2.13  raeburn  15070: =item *
                   15071: 
                   15072: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15073: when viewing in course context.
                   15074: 
                   15075:  input: six args -- filename (decluttered), course number, course domain,
                   15076:                     url, symb (if registered) and group (if this is a
                   15077:                     group item -- e.g., bulletin board, group page etc.).
                   15078: 
                   15079:  output: array of five scalars --
                   15080:          $cfile -- url for file editing if editable on current server
                   15081:          $home -- homeserver of resource (i.e., for author if published,
                   15082:                                           or course if uploaded.).
                   15083:          $switchserver --  1 if server switch will be needed.
                   15084:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15085:          $forceview -- 1 if icon/link should be to go to view mode
                   15086: 
                   15087: =item *
                   15088: 
                   15089: is_course_upload($file,$cnum,$cdom)
                   15090: 
                   15091: Used in course context to determine if current file was uploaded to
                   15092: the course (i.e., would be found in /userfiles/docs on the course's
                   15093: homeserver.
                   15094: 
                   15095:   input: 3 args -- filename (decluttered), course number and course domain.
                   15096:   output: boolean -- 1 if file was uploaded.
                   15097: 
1.243     albertel 15098: =back
                   15099: 
                   15100: =head2 Storing/Retreiving Data
                   15101: 
                   15102: =over 4
1.191     harris41 15103: 
                   15104: =item *
                   15105: 
1.1172.2.64  raeburn  15106: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15107: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15108: the remaining args aren't required and if they aren't passed or are '' they will
                   15109: be derived from the env (with the exception of $laststore, which is an
                   15110: optional arg used when a user's submission is stored in grading).
                   15111: $laststore is $version=$timestamp, where $version is the most recent version
                   15112: number retrieved for the corresponding $symb in the $namespace db file, and
                   15113: $timestamp is the timestamp for that transaction (UNIX time).
                   15114: $laststore is currently only passed when cstore() is called by
                   15115: structuretags::finalize_storage().
1.191     harris41 15116: 
                   15117: =item *
                   15118: 
1.1172.2.64  raeburn  15119: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15120: but uses critical subroutine
1.191     harris41 15121: 
                   15122: =item *
                   15123: 
1.243     albertel 15124: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15125: all args are optional
1.191     harris41 15126: 
                   15127: =item *
                   15128: 
1.717     albertel 15129: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15130: dumps the complete (or key matching regexp) namespace into a hash
                   15131: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15132: normally &store()ed into
                   15133: 
                   15134: $range should be either an integer '100' (give me the first 100
                   15135:                                            matching records)
                   15136:               or be  two integers sperated by a - with no spaces
                   15137:                  '30-50' (give me the 30th through the 50th matching
                   15138:                           records)
                   15139: 
                   15140: 
                   15141: =item *
                   15142: 
1.1172.2.59  raeburn  15143: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15144: replaces a &store() version of data with a replacement set of data
                   15145: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15146: reference. If $tolog is true, the transaction is logged in the courselog
                   15147: with an action=PUTSTORE.
1.717     albertel 15148: 
                   15149: =item *
                   15150: 
1.243     albertel 15151: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15152: works very similar to store/cstore, but all data is stored in a
                   15153: temporary location and can be reset using tmpreset, $storehash should
                   15154: be a hash reference, returns nothing on success
1.191     harris41 15155: 
                   15156: =item *
                   15157: 
1.243     albertel 15158: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15159: similar to restore, but all data is stored in a temporary location and
                   15160: can be reset using tmpreset. Returns a hash of values on success,
                   15161: error string otherwise.
1.191     harris41 15162: 
                   15163: =item *
                   15164: 
1.243     albertel 15165: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15166: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15167: 
                   15168: =item *
                   15169: 
1.243     albertel 15170: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15171: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15172: 
                   15173: =item *
                   15174: 
1.243     albertel 15175: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15176: namesp ($udom and $uname are optional)
1.191     harris41 15177: 
                   15178: =item *
                   15179: 
1.702     albertel 15180: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15181: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15182: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15183: 
1.702     albertel 15184: $range should be either an integer '100' (give me the first 100
                   15185:                                            matching records)
                   15186:               or be  two integers sperated by a - with no spaces
                   15187:                  '30-50' (give me the 30th through the 50th matching
                   15188:                           records)
1.449     matthew  15189: =item *
                   15190: 
                   15191: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15192: $store can be a scalar, an array reference, or if the amount to be 
                   15193: incremented is > 1, a hash reference.
                   15194: 
                   15195: ($udom and $uname are optional)
1.191     harris41 15196: 
                   15197: =item *
                   15198: 
1.243     albertel 15199: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15200: ($udom and $uname are optional)
1.191     harris41 15201: 
                   15202: =item *
                   15203: 
1.243     albertel 15204: cput($namespace,$storehash,$udom,$uname) : critical put
                   15205: ($udom and $uname are optional)
1.191     harris41 15206: 
                   15207: =item *
                   15208: 
1.748     albertel 15209: newput($namespace,$storehash,$udom,$uname) :
                   15210: 
                   15211: Attempts to store the items in the $storehash, but only if they don't
                   15212: currently exist, if this succeeds you can be certain that you have 
                   15213: successfully created a new key value pair in the $namespace db.
                   15214: 
                   15215: 
                   15216: Args:
                   15217:  $namespace: name of database to store values to
                   15218:  $storehash: hashref to store to the db
                   15219:  $udom: (optional) domain of user containing the db
                   15220:  $uname: (optional) name of user caontaining the db
                   15221: 
                   15222: Returns:
                   15223:  'ok' -> succeeded in storing all keys of $storehash
                   15224:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15225:                         least <key> already existed in the db (other
                   15226:                         requested keys may also already exist)
1.967     bisitz   15227:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15228:  'con_lost' -> unable to contact request server
                   15229:  'refused' -> action was not allowed by remote machine
                   15230: 
                   15231: 
                   15232: =item *
                   15233: 
1.243     albertel 15234: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15235: reference filled in from namesp (encrypts the return communication)
                   15236: ($udom and $uname are optional)
1.191     harris41 15237: 
                   15238: =item *
                   15239: 
1.243     albertel 15240: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15241: critical subroutine
                   15242: 
1.806     raeburn  15243: =item *
                   15244: 
1.860     raeburn  15245: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15246: array reference filled in from namespace found in domain level on either
                   15247: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15248: 
                   15249: =item *
                   15250: 
1.860     raeburn  15251: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15252: domain level either on specified domain server ($uhome) or primary domain 
                   15253: server ($udom and $uhome are optional)
1.806     raeburn  15254: 
1.943     raeburn  15255: =item * 
                   15256: 
1.1172.2.35  raeburn  15257: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15258: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15259: the target domain.
                   15260: 
                   15261: May also include additional key => value pairs for the following groups:
                   15262: 
                   15263: =over
                   15264: 
                   15265: =item
                   15266: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15267: 
                   15268: =over
                   15269: 
                   15270: =item defaultquota, authorquota
                   15271: 
                   15272: =back
                   15273: 
                   15274: =item
                   15275: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15276: portfolio for users).
                   15277: 
                   15278: =over
                   15279: 
                   15280: =item
                   15281: aboutme, blog, webdav, portfolio
                   15282: 
                   15283: =back
                   15284: 
                   15285: =item
                   15286: requestcourses: ability to request courses, and how requests are processed.
                   15287: 
                   15288: =over
                   15289: 
                   15290: =item
1.1172.2.37  raeburn  15291: official, unofficial, community, textbook
1.1172.2.35  raeburn  15292: 
                   15293: =back
                   15294: 
                   15295: =item
                   15296: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15297: 
                   15298: =over
                   15299: 
                   15300: =item
1.1172.2.44  raeburn  15301: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15302: 
                   15303: =back
                   15304: 
                   15305: =item
                   15306: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15307: for course's uploaded content.
                   15308: 
                   15309: =over
                   15310: 
                   15311: =item
1.1172.2.68  raeburn  15312: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15313: communityquota, textbookquota
1.1172.2.35  raeburn  15314: 
                   15315: =back
                   15316: 
                   15317: =item
                   15318: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15319: on your servers.
                   15320: 
                   15321: =over
                   15322: 
                   15323: =item
                   15324: remotesessions, hostedsessions
                   15325: 
                   15326: =back
                   15327: 
                   15328: =back
                   15329: 
                   15330: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15331: utility to create a configuration.db file on a domain's primary library server
                   15332: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15333: -- corresponding values are authentication type (internal, krb4, krb5,
                   15334: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15335: will be available. Values are retrieved from cache (if current), unless the
                   15336: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15337: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15338: 
                   15339: Typical usage:
1.943     raeburn  15340: 
1.1172.2.35  raeburn  15341: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15342: 
1.243     albertel 15343: =back
                   15344: 
                   15345: =head2 Network Status Functions
                   15346: 
                   15347: =over 4
1.191     harris41 15348: 
                   15349: =item *
                   15350: 
1.1137    raeburn  15351: dirlist() : return directory list based on URI (first arg).
                   15352: 
                   15353: Inputs: 1 required, 5 optional.
                   15354: 
                   15355: =over
                   15356: 
                   15357: =item 
                   15358: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15359: 
                   15360: =item
                   15361: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15362: 
                   15363: =item
                   15364: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15365: 
                   15366: =item
                   15367: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15368: 
                   15369: =item
                   15370: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15371: 
                   15372: =item 
                   15373: $alternateRoot - path to prepend in place of path from $uri.
                   15374: 
                   15375: =back
                   15376: 
                   15377: Returns: Array of up to two items.
                   15378: 
                   15379: =over
                   15380: 
                   15381: a reference to an array of files/subdirectories
                   15382: 
                   15383: =over
                   15384: 
                   15385: Each element in the array of files/subdirectories is a & separated list of
                   15386: item name and the result of running stat on the item.  If dirlist was requested
                   15387: for a file instead of a directory, the item name will be ''. For a directory 
                   15388: listing, if the item is a metadata file, the element will end &N&M 
                   15389: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15390: default copyright set (1).  
                   15391: 
                   15392: =back
                   15393: 
                   15394: a scalar containing error condition (if encountered).
                   15395: 
                   15396: =over
                   15397: 
                   15398: =item 
                   15399: no_host (no homeserver identified for $username:$domain).
                   15400: 
                   15401: =item 
                   15402: no_such_host (server contacted for listing not identified as valid host).
                   15403: 
                   15404: =item 
                   15405: con_lost (connection to remote server failed).
                   15406: 
                   15407: =item 
                   15408: refused (invalid $username:$domain received on lond side).
                   15409: 
                   15410: =item 
                   15411: no_such_dir (directory at specified path on lond side does not exist). 
                   15412: 
                   15413: =item 
                   15414: empty (directory at specified path on lond side is empty).
                   15415: 
                   15416: =over
                   15417: 
                   15418: This is currently not encountered because the &ls3, &ls2, 
                   15419: &ls (_handler) routines on the lond side do not filter out
                   15420: . and .. from a directory listing. 
                   15421: 
                   15422: =back
                   15423: 
                   15424: =back
                   15425: 
                   15426: =back
1.191     harris41 15427: 
                   15428: =item *
                   15429: 
1.243     albertel 15430: spareserver() : find server with least workload from spare.tab
                   15431: 
1.986     foxr     15432: 
                   15433: =item *
                   15434: 
                   15435: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15436: if there is no corresponding loncapa host.
                   15437: 
1.243     albertel 15438: =back
                   15439: 
1.986     foxr     15440: 
1.243     albertel 15441: =head2 Apache Request
                   15442: 
                   15443: =over 4
1.191     harris41 15444: 
                   15445: =item *
                   15446: 
1.243     albertel 15447: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15448: localhost, posts hash
                   15449: 
                   15450: =back
                   15451: 
                   15452: =head2 Data to String to Data
                   15453: 
                   15454: =over 4
1.191     harris41 15455: 
                   15456: =item *
                   15457: 
1.243     albertel 15458: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15459: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15460: 
                   15461: =item *
                   15462: 
1.243     albertel 15463: hashref2str($hashref) : convert a hashref into a string complete with
                   15464: escaping and '=' and '&' separators, supports elements that are
                   15465: arrayrefs and hashrefs
1.191     harris41 15466: 
                   15467: =item *
                   15468: 
1.243     albertel 15469: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15470: with escaping and '&' separators, supports elements that are arrayrefs
                   15471: and hashrefs
1.191     harris41 15472: 
                   15473: =item *
                   15474: 
1.243     albertel 15475: str2hash($string) : convert string to hash using unescaping and
                   15476: splitting on '=' and '&', supports elements that are arrayrefs and
                   15477: hashrefs
1.191     harris41 15478: 
                   15479: =item *
                   15480: 
1.243     albertel 15481: str2array($string) : convert string to hash using unescaping and
                   15482: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15483: 
                   15484: =back
                   15485: 
                   15486: =head2 Logging Routines
                   15487: 
                   15488: 
                   15489: These routines allow one to make log messages in the lonnet.log and
                   15490: lonnet.perm logfiles.
1.191     harris41 15491: 
1.1119    foxr     15492: =over 4
                   15493: 
1.191     harris41 15494: =item *
                   15495: 
1.243     albertel 15496: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15497: 
                   15498: =item *
                   15499: 
1.243     albertel 15500: logthis() : append message to the normal lonnet.log file, it gets
                   15501: preiodically rolled over and deleted.
1.191     harris41 15502: 
                   15503: =item *
                   15504: 
1.243     albertel 15505: logperm() : append a permanent message to lonnet.perm.log, this log
                   15506: file never gets deleted by any automated portion of the system, only
                   15507: messages of critical importance should go in here.
                   15508: 
1.1119    foxr     15509: 
1.243     albertel 15510: =back
                   15511: 
                   15512: =head2 General File Helper Routines
                   15513: 
                   15514: =over 4
1.191     harris41 15515: 
                   15516: =item *
                   15517: 
1.481     raeburn  15518: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15519: (a) files in /uploaded
                   15520:   (i) If a local copy of the file exists - 
                   15521:       compares modification date of local copy with last-modified date for 
                   15522:       definitive version stored on home server for course. If local copy is 
                   15523:       stale, requests a new version from the home server and stores it. 
                   15524:       If the original has been removed from the home server, then local copy 
                   15525:       is unlinked.
                   15526:   (ii) If local copy does not exist -
                   15527:       requests the file from the home server and stores it. 
                   15528:   
                   15529:   If $caller is 'uploadrep':  
                   15530:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15531:     for request for files originally uploaded via DOCS. 
                   15532:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15533:   
                   15534:   Otherwise:
                   15535:      This indicates a call from the content generation phase of the request.
                   15536:      -  returns the entire contents of the file or -1.
                   15537:      
                   15538: (b) files in /res
                   15539:    - returns the entire contents of a file or -1; 
                   15540:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15541: 
1.712     albertel 15542: 
                   15543: =item *
                   15544: 
                   15545: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15546:                   reference
                   15547: 
                   15548: returns either a stat() list of data about the file or an empty list
                   15549: if the file doesn't exist or couldn't find out about it (connection
                   15550: problems or user unknown)
                   15551: 
1.191     harris41 15552: =item *
                   15553: 
1.243     albertel 15554: filelocation($dir,$file) : returns file system location of a file
                   15555: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15556: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15557: and a file of ../bob will become /a/bob)
1.191     harris41 15558: 
                   15559: =item *
                   15560: 
                   15561: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15562: filelocation except for hrefs
                   15563: 
                   15564: =item *
                   15565: 
1.1172.2.49  raeburn  15566: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15567: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15568: 
1.243     albertel 15569: =back
                   15570: 
1.608     albertel 15571: =head2 Usererfile file routines (/uploaded*)
                   15572: 
                   15573: =over 4
                   15574: 
                   15575: =item *
                   15576: 
                   15577: userfileupload(): main rotine for putting a file in a user or course's
                   15578:                   filespace, arguments are,
                   15579: 
1.620     albertel 15580:  formname - required - this is the name of the element in $env where the
1.608     albertel 15581:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15582:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15583:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15584:  context - if coursedoc, store the file in the course of the active role
                   15585:              of the current user; 
                   15586:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15587:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15588:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15589:          if undefined, it will be placed in "unknown"
                   15590: 
                   15591:  (This routine calls clean_filename() to remove any dangerous
                   15592:  characters from the filename, and then calls finuserfileupload() to
                   15593:  complete the transaction)
                   15594: 
                   15595:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15596:  and /adm/notfound.html if unsuccessful
                   15597: 
                   15598: =item *
                   15599: 
                   15600: clean_filename(): routine for cleaing a filename up for storage in
                   15601:                  userfile space, argument is:
                   15602: 
                   15603:  filename - proposed filename
                   15604: 
                   15605: returns: the new clean filename
                   15606: 
                   15607: =item *
                   15608: 
1.1090    raeburn  15609: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15610: userspace, probably shouldn't be called directly
                   15611: 
                   15612:   docuname: username or courseid of destination for the file
                   15613:   docudom: domain of user/course of destination for the file
                   15614:   formname: same as for userfileupload()
1.1090    raeburn  15615:   fname: filename (including subdirectories) for the file
                   15616:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15617:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15618:   allfiles: reference to hash used to store objects found by parser
                   15619:   codebase: reference to hash used for codebases of java objects found by parser
                   15620:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15621:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15622:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15623:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15624:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15625:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15626:   mimetype: reference to scalar to accommodate mime type determined
                   15627:             from File::MMagic if $parser = parse.
1.608     albertel 15628: 
                   15629:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15630:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15631:  was 'overwrite').
                   15632:  
1.608     albertel 15633: 
                   15634: =item *
                   15635: 
                   15636: renameuserfile(): renames an existing userfile to a new name
                   15637: 
                   15638:   Args:
                   15639:    docuname: username or courseid of destination for the file
                   15640:    docudom: domain of user/course of destination for the file
                   15641:    old: current file name (including any subdirs under userfiles)
                   15642:    new: desired file name (including any subdirs under userfiles)
                   15643: 
                   15644: =item *
                   15645: 
                   15646: mkdiruserfile(): creates a directory is a userfiles dir
                   15647: 
                   15648:   Args:
                   15649:    docuname: username or courseid of destination for the file
                   15650:    docudom: domain of user/course of destination for the file
                   15651:    dir: dir to create (including any subdirs under userfiles)
                   15652: 
                   15653: =item *
                   15654: 
                   15655: removeuserfile(): removes a file that exists in userfiles
                   15656: 
                   15657:   Args:
                   15658:    docuname: username or courseid of destination for the file
                   15659:    docudom: domain of user/course of destination for the file
                   15660:    fname: filname to delete (including any subdirs under userfiles)
                   15661: 
                   15662: =item *
                   15663: 
                   15664: removeuploadedurl(): convience function for removeuserfile()
                   15665: 
                   15666:   Args:
                   15667:    url:  a full /uploaded/... url to delete
                   15668: 
1.747     albertel 15669: =item * 
                   15670: 
                   15671: get_portfile_permissions():
                   15672:   Args:
                   15673:     domain: domain of user or course contain the portfolio files
                   15674:     user: name of user or num of course contain the portfolio files
                   15675:   Returns:
                   15676:     hashref of a dump of the proper file_permissions.db
                   15677:    
                   15678: 
                   15679: =item * 
                   15680: 
                   15681: get_access_controls():
                   15682: 
                   15683: Args:
                   15684:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15685:   group: (optional) the group you want the files associated with
                   15686:   file: (optional) the file you want access info on
                   15687: 
                   15688: Returns:
1.749     raeburn  15689:     a hash (keys are file names) of hashes containing
                   15690:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15691:         values are XML containing access control settings (see below) 
1.747     albertel 15692: 
                   15693: Internal notes:
                   15694: 
1.749     raeburn  15695:  access controls are stored in file_permissions.db as key=value pairs.
                   15696:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15697:         where scope -> public,guest,course,group,domains or users.
                   15698:               end -> UNIX time for end of access (0 -> no end date)
                   15699:               start -> UNIX time for start of access
                   15700: 
                   15701:     value -> XML description of access control
                   15702:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15703:             <start></start>
                   15704:             <end></end>
                   15705: 
                   15706:             <password></password>  for scope type = guest
                   15707: 
                   15708:             <domain></domain>     for scope type = course or group
                   15709:             <number></number>
                   15710:             <roles id="">
                   15711:              <role></role>
                   15712:              <access></access>
                   15713:              <section></section>
                   15714:              <group></group>
                   15715:             </roles>
                   15716: 
                   15717:             <dom></dom>         for scope type = domains
                   15718: 
                   15719:             <users>             for scope type = users
                   15720:              <user>
                   15721:               <uname></uname>
                   15722:               <udom></udom>
                   15723:              </user>
                   15724:             </users>
                   15725:            </scope> 
                   15726:               
                   15727:  Access data is also aggregated for each file in an additional key=value pair:
                   15728:  key -> path to file/file_name\0accesscontrol 
                   15729:  value -> reference to hash
                   15730:           hash contains key = value pairs
                   15731:           where key = uniqueID:scope_end_start
                   15732:                 value = UNIX time record was last updated
                   15733: 
                   15734:           Used to improve speed of look-ups of access controls for each file.  
                   15735:  
                   15736:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15737: 
1.1172.2.13  raeburn  15738: =item *
                   15739: 
1.749     raeburn  15740: modify_access_controls():
                   15741: 
                   15742: Modifies access controls for a portfolio file
                   15743: Args
                   15744: 1. file name
                   15745: 2. reference to hash of required changes,
                   15746: 3. domain
                   15747: 4. username
                   15748:   where domain,username are the domain of the portfolio owner 
                   15749:   (either a user or a course) 
                   15750: 
                   15751: Returns:
                   15752: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15753: 2. result of deletions ('ok' or 'error', with error message).
                   15754: 3. reference to hash of any new or updated access controls.
                   15755: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15756:    key = integer (inbound ID)
1.1172.2.13  raeburn  15757:    value = uniqueID
                   15758: 
                   15759: =item *
                   15760: 
                   15761: get_timebased_id():
                   15762: 
                   15763: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15764: course via the Course Editor (e.g., folders, composite pages,
                   15765: group bulletin boards).
                   15766: 
                   15767: Args: (first three required; six others optional)
                   15768: 
                   15769: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15770:    docssequence, or name of group
                   15771: 
                   15772: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15773:    e.g., num, boardids
                   15774: 
                   15775: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15776:    file will be named nohist_namespace.db
                   15777: 
                   15778: 4. cdom: domain of course; default is current course domain from %env
                   15779: 
                   15780: 5. cnum: course number; default is current course number from %env
                   15781: 
                   15782: 6. idtype: set to concat if an additional digit is to be appended to the
                   15783:    unix timestamp to form the suffix, if the plain timestamp is already
                   15784:    in use.  Default is to not do this, but simply increment the unix
                   15785:    timestamp by 1 until a unique key is obtained.
                   15786: 
                   15787: 7. who: holder of locking key; defaults to user:domain for user.
                   15788: 
                   15789: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15790:    retrying); default is 3.
                   15791: 
                   15792: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15793: 
                   15794: Returns:
                   15795: 
                   15796: 1. suffix obtained (numeric)
                   15797: 
                   15798: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15799: 
                   15800: 3. error: contains (localized) error message if an error occurred.
                   15801: 
1.747     albertel 15802: 
1.608     albertel 15803: =back
                   15804: 
1.243     albertel 15805: =head2 HTTP Helper Routines
                   15806: 
                   15807: =over 4
                   15808: 
1.191     harris41 15809: =item *
                   15810: 
                   15811: escape() : unpack non-word characters into CGI-compatible hex codes
                   15812: 
                   15813: =item *
                   15814: 
                   15815: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15816: 
1.243     albertel 15817: =back
                   15818: 
                   15819: =head1 PRIVATE SUBROUTINES
                   15820: 
                   15821: =head2 Underlying communication routines (Shouldn't call)
                   15822: 
                   15823: =over 4
                   15824: 
                   15825: =item *
                   15826: 
                   15827: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15828: 
                   15829: =item *
                   15830: 
                   15831: reply() : uses subreply to send a message to remote machine, logs all failures
                   15832: 
                   15833: =item *
                   15834: 
                   15835: critical() : passes a critical message to another server; if cannot
                   15836: get through then place message in connection buffer directory and
                   15837: returns con_delayed, if incapable of saving message, returns
                   15838: con_failed
                   15839: 
                   15840: =item *
                   15841: 
                   15842: reconlonc() : tries to reconnect lonc client processes.
                   15843: 
                   15844: =back
                   15845: 
                   15846: =head2 Resource Access Logging
                   15847: 
                   15848: =over 4
                   15849: 
                   15850: =item *
                   15851: 
                   15852: flushcourselogs() : flush (save) buffer logs and access logs
                   15853: 
                   15854: =item *
                   15855: 
                   15856: courselog($what) : save message for course in hash
                   15857: 
                   15858: =item *
                   15859: 
                   15860: courseacclog($what) : save message for course using &courselog().  Perform
                   15861: special processing for specific resource types (problems, exams, quizzes, etc).
                   15862: 
1.191     harris41 15863: =item *
                   15864: 
                   15865: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15866: as a PerlChildExitHandler
1.243     albertel 15867: 
                   15868: =back
                   15869: 
                   15870: =head2 Other
                   15871: 
                   15872: =over 4
                   15873: 
                   15874: =item *
                   15875: 
                   15876: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15877: 
                   15878: =back
                   15879: 
                   15880: =cut
1.877     foxr     15881: 

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